php 如何在 Magento 中创建一个简单的“Hello World”模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/576908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:08:13  来源:igfitidea点击:

How do I create a simple 'Hello World' module in Magento?

phpmagentocontrollermagento-1.9

提问by Click Upvote

How can the following be accomplished in Magento?

如何在 Magento 中完成以下操作?

  • Display a "Hello World" message using a controller/view/model approach. So, if I went to http://example.com/myControllerit would show the string 'Hello World'. Being able to show this string within the template of my website (for example, the header, footer, etc.) will be a bonus.

  • How do I add a method to this controller (or a new controller if necessary), which interacts with a model, and performs the query Select * FROM articles where id='10'and returns the row (containing the columns id, title, content) to the controller? And then use the controller to include a view, which would display this row. So going to http://example.com/myController/show_row(or something similar) would display the row within a view. (No need to be fancy, just a echo $row->id;or something similar would work.)

  • 使用控制器/视图/模型方法显示“Hello World”消息。所以,如果我去http://example.com/myController它会显示字符串“Hello World”。能够在我的网站模板(例如,页眉、页脚等)中显示此字符串将是一个奖励。

  • 如何向此控制器(或必要时添加新控制器)添加一个方法,该方法与模型交互,并执行查询Select * FROM articles where id='10'并将行(包含列id, title, content)返回给控制器?然后使用控制器包含一个视图,它将显示这一行。所以转到http://example.com/myController/show_row(或类似的东西)将在视图中显示该行。(无需花哨,只需一个echo $row->id;或类似的东西即可。)

Any other information about Magento's code structure will also be very helpful.

有关 Magento 代码结构的任何其他信息也将非常有帮助。

回答by Alan Storm

First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.

首先,我强烈建议您从 PHP Architect购买PDF/电子书。它是 20 美元,但它是我能找到的唯一简单的“Magento 的工作原理”资源。我也开始在我自己的网站上编写Magento 教程

Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP andJava), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.

其次,如果您有选择,并且不是有经验的程序员或没有经验的程序员(最好是 PHPJava),请选择另一个购物车。Magento 设计得很好,但它被设计成一个购物车解决方案,其他程序员可以在其上构建模块。它不是为了让聪明但不是程序员的人容易理解而设计的。

Third, Magento MVC is very different from the Ruby on Rails, Django, CodeIgniter, CakePHP, etc. MVC model that's popular with PHP developers these days. I think it's based on the Zendmodel, and the whole thing is very Java OOP-like. There's twocontrollers you need to be concerned about. The module/frontName controller, and then the MVC controller.

第三,Magento MVC 与Ruby on RailsDjangoCodeIgniterCakePHP等非常不同。 MVC 模型现在很受 PHP 开发人员的欢迎。我认为它是基于Zend模型的,整个过程非常类似于 Java OOP。有2级需要被关心的控制器。module/frontName 控制器,然后是 MVC 控制器。

Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overridingexisting classes. What I'm covering here is creatingnew functionality, not overriding. Keep this in mind when you're looking at the code samples out there.

第四,Magento 应用程序本身是使用您将使用的相同模块系统构建的,因此浏览核心代码是一种有用的学习策略。此外,您将使用 Magento 做的很多事情都会覆盖现有的类。我在这里介绍的是创建新功能,而不是覆盖。在查看代码示例时请记住这一点。

I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.

我将从您的第一个问题开始,向您展示如何设置控制器/路由器以响应特定 URL。这将是一本小小说。稍后我可能有时间讨论模型/模板相关主题,但现在,我没有。但是,我将简要谈谈您的 SQL 问题。

Magento uses an EAVdatabase architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.

Magento 使用EAV数据库架构。只要有可能,尝试使用系统提供的模型对象来获取您需要的信息。我知道这一切都在 SQL 表中,但最好不要考虑使用原始 SQL 查询获取数据,否则你会发疯。

Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help Stack Overflow.

最后免责声明。我已经使用 Magento 大约两三个星期了,所以请注意空客。这是一个练习,既可以帮助我理解 Stack Overflow 的想法,也可以帮助我理解这一点。

Create a module

创建模块

All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modulesnamed as follows

Magento 的所有添加和定制都是通过模块完成的。因此,您需要做的第一件事是创建一个新模块。创建一个app/modules名为如下的 XML 文件

cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml
<?xml version="1.0"?>
<config>
     <modules>
        <MyCompanyName_HelloWorld>
            <active>true</active>
            <codePool>local</codePool>
        </MyCompanyName_HelloWorld>
     </modules>
</config>

MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorldis the name of your module.

MyCompanyName 是您修改的唯一命名空间,它不必是您公司的名称,而是推荐的约定 my magento。HelloWorld是您的模块的名称。

Clear the application cache

清除应用程序缓存

Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application

现在模块文件已经就位,我们需要让 Magento 知道它(并检查我们的工作)。在管理应用程序中

  1. Go to System->Cache Management
  2. Select Refresh from the All Cache menu
  3. Click Save Cache settings
  1. 转到系统->缓存管理
  2. 从所有缓存菜单中选择刷新
  3. 单击保存缓存设置

Now, we make sure that Magento knows about the module

现在,我们确保 Magento 知道该模块

  1. Go to System->Configuration
  2. Click Advanced
  3. In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld"
  1. 转到系统->配置
  2. 单击高级
  3. 在“禁用模块输出”设置框中,查找名为“MyCompanyName_HelloWorld”的新模块

If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.

如果您可以忍受性能下降,您可能希望在开发/学习时关闭应用程序缓存。没有什么比忘记清除缓存并想知道为什么您的更改没有显示更令人沮丧的了。

Setup the directory structure

设置目录结构

Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.

接下来,我们需要为模块设置一个目录结构。您不需要所有这些目录,但现在将它们全部设置并没有什么坏处。

mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
mkdir -p app/code/local/MyCompanyName/HelloWorld/sql

And add a configuration file

并添加一个配置文件

touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml

and inside the configuration file, add the following, which is essentially a "blank" configuration.

并在配置文件中添加以下内容,这实际上是一个“空白”配置。

<?xml version="1.0"?>
<config>
    <modules>
        <MyCompanyName_HelloWorld>
            <version>0.1.0</version>
        </MyCompanyName_HelloWorld>
    </modules>
</config>

Oversimplifying things, this configuration file will let you tell Magento what code you want to run.

过于简单的事情,这个配置文件会让你告诉 Magento 你想运行什么代码。

Setting up the router

设置路由器

Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of

接下来,我们需要设置模块的路由器。这将让系统知道我们正在处理任何形式的 URL

http://example.com/magento/index.php/helloworld

So, in your configuration file, add the following section.

因此,在您的配置文件中,添加以下部分。

<config>
<!-- ... -->
    <frontend>
        <routers>
            <!-- the <helloworld> tagname appears to be arbitrary, but by
            convention is should match the frontName tag below-->
            <helloworld>
                <use>standard</use>
                <args>
                    <module>MyCompanyName_HelloWorld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
    </frontend>
<!-- ... -->
</config>

What you're saying here is "any URL with the frontName of helloworld ...

你在这里说的是“任何带有 helloworld 的 frontName 的 URL ......

http://example.com/magento/index.php/helloworld

should use the frontName controller MyCompanyName_HelloWorld".

应该使用 frontName 控制器 MyCompanyName_HelloWorld”。

So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.

所以,有了上面的配置,当你加载上面的 helloworld 页面时,你会得到一个 404 页面。那是因为我们还没有为我们的控制器创建文件。让我们现在就这样做。

touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php

Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception

现在尝试加载页面。进步!你会得到一个 PHP/Magento 异常而不是 404

Controller file was loaded but class does not exist

So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.

因此,打开我们刚刚创建的文件,并粘贴以下代码。类的名称需要基于您在路由器中提供的名称。

<?php
class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
    }
}

What we've just setup is the module/frontName controller. This is the default controller and the default action of the module. If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName

我们刚刚设置的是 module/frontName 控制器。这是默认控制器和模块的默认操作。如果你想添加控制器或动作,你必须记住,Magento URL 的树的第一部分是不可变的,它们总是这样http://example.com/magento/index.php/frontName/controllerName/actionName

So if you want to match this url

所以如果你想匹配这个网址

http://example.com/magento/index.php/helloworld/foo

You will have to have a FooController, which you can do this way :

你必须有一个 FooController,你可以这样做:

touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
<?php
class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo 'Foo Index Action';
    }

    public function addAction(){
        echo 'Foo add Action';
    }

    public function deleteAction(){
        echo 'Foo delete Action';
    }
}

Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it. So http://example.com/magento/index.php/helloworld/foowill match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way : http://example.com/magento/index.php/helloworld/index/foobecause the second part of the url is and will always be the controllerName. This behaviour is an inheritance of the Zend Framework bundled in Magento.

请注意,默认控制器 IndexController 和默认操作 indexAction 可以是隐式的,但如果后面有东西,则必须是显式的。因此http://example.com/magento/index.php/helloworld/foo将匹配控制器 FooController 和操作 indexAction 而不是 IndexController 的操作 fooAction。如果你想要一个 fooAction,在控制器 IndexController 中,你必须像这样显式调用这个控制器: http://example.com/magento/index.php/helloworld/index/foo因为 url 的第二部分是并且将永远是 controllerName。此行为是 Magento 中捆绑的 Zend 框架的继承。

You should now be able to hit the following URLs and see the results of your echo statements

您现在应该能够点击以下 URL 并查看您的 echo 语句的结果

http://example.com/magento/index.php/helloworld/foo
http://example.com/magento/index.php/helloworld/foo/add
http://example.com/magento/index.php/helloworld/foo/delete

So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.

所以,这应该给你一个关于 Magento 如何调度到控制器的基本概念。从这里开始,我建议查看现有的 Magento 控制器类,看看应该如何使用模型和模板/布局系统。

回答by Manos Dilaverakis

I've been wrestling with Magento for the last month or so and I'm still trying to figure it out. So this is a case of the blind leading the blind. There's little in the way of documentation and the forum/wiki is chaotic at best. Not only that, but there are several solutions that are either outdated or far from optimal. I'm not sure if you have a project or just trying to figure it out, but it's probably easier if you started with modifying existing functionality as opposed to creating something completely new. For that I'd definately go with the "Recommended articles for developers" in the wiki. The new payment method one was a real eye-opener.

过去一个月左右,我一直在与 Magento 搏斗,我仍在努力弄清楚。所以这是一个瞎子领瞎子的例子。文档的方式很少,论坛/维基充其量是混乱的。不仅如此,还有几种解决方案要么过时,要么远非最佳。我不确定您是否有项目或只是想弄清楚,但如果您从修改现有功能开始,而不是创建全新的东西,那可能会更容易。为此,我肯定会选择 wiki 中的“开发人员推荐文章”。一种新的付款方式令人大开眼界。

For debugging I'd definitely recommend using FirePHPand looking at your HTML source when something goes wrong. The ole echo debug method doesn't really work all that well.

对于调试,我绝对推荐使用 FirePHP并在出现问题时查看您的 HTML 源代码。ole echo 调试方法实际上并没有那么好用。

The general architecture is so mind-numbingly complex, that even if I completely understood it, I'd need to write a book to cover it. The best I can do is give you advice I wish someone had given me when I first started...

一般的架构是如此复杂,令人麻木,即使我完全理解它,我也需要写一本书来涵盖它。我能做的最好的事情就是给你建议,我希望在我刚开始的时候有人给过我……

Stay away from core files. Don't modify them, instead write your own module and override what you need.

远离核心文件。不要修改它们,而是编写自己的模块并覆盖您需要的模块。

Magento uses config files consisting of XML to decide what it needs to do. In order to get it to run your own stuff as opposed to core functionality you need the correct xml. Unfortunately there is no guide on how to build you XML; you need to look at examples and do some serious testing. To complicate things the content of these files is largely case-sensitive. However if you master these you can override any part of the basic functionality which makes for a very powerful system.

Magento 使用由 XML 组成的配置文件来决定它需要做什么。为了让它运行你自己的东西而不是核心功能,你需要正确的 xml。不幸的是,没有关于如何构建 XML 的指南;您需要查看示例并进行一些认真的测试。更复杂的是,这些文件的内容在很大程度上区分大小写。但是,如果您掌握了这些,您可以覆盖基本功能的任何部分,从而构成一个非常强大的系统。

Magento uses methods like Mage::getModel('mymodel'), Mage::getSingleton('mysingleton'), Mage::helper('myhelper')to return objects of certain classes. It finds these by default in its core namespace. If you want it to use your own, you need to override these in your config.xmlfile.

Magento的使用方法一样Mage::getModel('mymodel')Mage::getSingleton('mysingleton')Mage::helper('myhelper')返回特定类的对象。默认情况下,它会在其核心命名空间中找到这些。如果你想让它使用你自己的,你需要在你的config.xml文件中覆盖这些。

The name of your classes must correspond to the folder they're in.

类的名称必须与它们所在的文件夹相对应。

A lot of the objects in Magento ultimately extend something called a Varien_Object. This is a general purpose class (kind of like a swiss army knife) and its purpose in life is to allow you to define your own methods/variables on the fly. For example you'll see it used as a glorified array to pass data from one method to another.

Magento 中的许多对象最终都会扩展名为Varien_Object. 这是一个通用类(有点像瑞士军刀),它在生活中的目的是允许您动态定义自己的方法/变量。例如,您会看到它用作一个美化的数组,将数据从一种方法传递到另一种方法。

During development make sure you caching is disabled. It'll make magento excruciatingly slow, but it'll save you a lot of head trauma (from banging it on your desk).

在开发过程中,请确保禁用缓存。它会使 magento 极其缓慢,但它会为您节省很多头部创伤(将它撞在桌子上)。

You'll see $thisbeing used a lot. It means a different class depending on what file you see it. get_class($this)is your friend, especially in conjunction with FirePHP.

你会看到$this被大量使用。这意味着不同的类,具体取决于您看到的文件。get_class($this)是您的朋友,尤其是与 FirePHP 结合使用时。

Jot things down on paper. A lot. There are countless little factoids that you're gonna need 1-2 days after you encounter them.

把事情记在纸上。很多。在遇到它们后的 1-2 天,您将需要无数的小事实。

Magento loves OO. Don't be surprised if tracing a method takes you through 5-10 different classes.

Magento 喜欢面向对象。如果跟踪一个方法会带您浏览 5-10 个不同的类,请不要感到惊讶。

Read the designer's guide here. It's meant mostly for graphics designers, but you needit to understand where and why the output from your module will end up. For that don't forget to turn on "Template path hints" in the developer section of the admin panel.

此处阅读设计师指南。它主要适用于图形设计师,但您需要它来了解模块的输出最终会在哪里以及为什么会结束。为此,请不要忘记在管理面板的开发人员部分打开“模板路径提示”。

There's more, but I'll stop here before this turns into a dissertation.

还有更多,但我会在这变成一篇论文之前到此为止。

回答by Sajid

I will rather recommend Mage2Gen, this will help you generate the boilerplate and you can just focus on the core business logic. it just helps speed up the things.

我宁愿推荐Mage2Gen,这将帮助您生成样板,您可以专注于核心业务逻辑。它只是有助于加快速度。

回答by AbdurRahman Lakhani

A Magento Module is a group of directories containing blocks, controllers, helpers, and models that are needed to create a specific store feature. It is the unit of customization in the Magento platform. Magento Modules can be created to perform multiple functions with supporting logic to influence user experience and storefront appearance. It has a life cycle that allows them to be installed, deleted, or disabled. From the perspective of both merchants and extension developers, modules are the central unit of the Magento platform.

Magento 模块是一组目录,包含创建特定商店功能所需的块、控制器、助手和模型。它是 Magento 平台中的定制单元。可以创建 Magento 模块来执行具有支持逻辑的多种功能,以影响用户体验和店面外观。它具有允许安装、删除或禁用它们的生命周期。从商家和扩展开发者的角度来看,模块是 Magento 平台的中心单元。

Declaration of Module

模块声明

We have to declare the module by using the configuration file. As Magento 2 search for configuration module in etc directory of the module. So now we will create configuration file module.xml.

我们必须使用配置文件来声明模块。由于 Magento 2 在模块的 etc 目录中搜索配置模块。所以现在我们将创建配置文件module.xml。

The code will look like this:

代码如下所示:

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Cloudways_Mymodule" setup_version="1.0.0"></module> </config>

Registration of ModuleThe module must be registered in the Magento 2 system by using Magento Component Registrar class. Now we will create the file registration.php in the module root directory:

模块的注册 模块必须使用 Magento Component Registrar 类在 Magento 2 系统中注册。现在我们将在模块根目录中创建文件 registration.php :

app/code/Cloudways/Mymodule/registration.php

The Code will look like this:

代码将如下所示:

?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Cloudways_Mymodule',
__DIR__
);

Check Module StatusAfter following the steps above, we would have created a simple module. Now we are going to check the status of the module and whether it is enabled or disabled by using the following command line:

检查模块状态按照上述步骤操作后,我们将创建一个简单的模块。现在我们将使用以下命令行检查模块的状态以及它是启用还是禁用:

php bin/magento module:status

php bin/magento module:enable Cloudways_Mymodule

Share your feedback once you have gone through complete process

完成完整流程后分享您的反馈

回答by Sanaullah Ahmad

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-worldfrom github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/worldYou can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdownsand place it in your aap/code folder. than run these commands...

我试图从 magaplaza hello world 教程制作我的模块,但出了点问题。我从 github导入了这个模块https://github.com/astorm/magento2-hello-world 的代码并且它起作用了。从该模块,我创建了一个类别子类别 ajax 选择下拉模块。将其安装在 magento2 安装的 aap/code 目录中后,请按照此 URL .. http://www.example.com/hello_mvvm/hello/world您可以从这里下载其代码https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns并将其放在您的 aap/code 文件夹中。比运行这些命令...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

现在您可以使用以下 URL http://{{www.example.com}}/hello_mvvm/hello/world 检查模块功能

回答by Rajan Soni

And,

和,

I suggest you to learn about system configuration.

我建议你学习一下系统配置。

How to Show All Categories on System Configuration Field?

如何在系统配置字段中显示所有类别?

Here I solved with a good example. It working. You can check and learn the flow of code.

在这里,我用一个很好的例子解决了。它工作。您可以检查和学习代码的流程。

There are other too many examples also that you should learn.

还有其他太多的例子你应该学习。