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

本文翻译自:How do I create a simple 'Hello World' module in Magento?

How can the following be accomplished in Magento? 如何在Magento完成以下任务?

  • Display a "Hello World" message using a controller/view/model approach. 使用控制器/视图/模型方法显示“Hello World”消息。 So, if I went to http://example.com/myController it would show the string 'Hello World'. 所以,如果我去http://example.com/myController它会显示字符串'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? 如何向该控制器(或必要时的新控制器)添加方法,该方法与模型交互,并执行查询Select * FROM articles where id='10'并返回行(包含列id, title, content )到控制器? 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. 因此,访问http://example.com/myController/show_row (或类似的东西)会在视图中显示该行。 (No need to be fancy, just a echo $row->id; or something similar would work.) (不需要花哨,只需要一个echo $row->id;或类似的东西可以工作。)

Any other information about Magento's code structure will also be very helpful. 关于Magento代码结构的任何其他信息也将非常有用。




I will rather recommend Mage2Gen , this will help you generate the boilerplate and you can just focus on the core business logic. 我宁愿推荐Mage2Gen ,这将帮助您生成样板,您可以专注于核心业务逻辑。 it just helps speed up the things. 它只是有助于加快速度。


A Magento Module is a group of directories containing blocks, controllers, helpers, and models that are needed to create a specific store feature. Magento模块是一组目录,包含创建特定商店功能所需的块,控制器,帮助程序和模型。 It is the unit of customization in the Magento platform. 它是Magento平台中的定制单元。 Magento Modules can be created to perform multiple functions with supporting logic to influence user experience and storefront appearance. 可以创建Magento模块以执行具有支持逻辑的多种功能,以影响用户体验和店面外观。 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平台的核心单元。

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. 由于Magento 2在模块的etc目录中搜索配置模块。 So now we will create configuration file module.xml. 所以现在我们将创建配置文件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 Module The module must be registered in the Magento 2 system by using Magento Component Registrar class. 模块的注册模块必须在Magento的2系统通过使用Magento的元器件处长类中注册。 Now we will create the file registration.php in the module root directory: 现在我们将在模块根目录中创建文件registration.php:


The Code will look like this: 守则将如下所示:


Check Module Status After 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 完成整个过程后,请分享您的反馈


I was trying to make my module from magaplaza hello world tutorial, but something went wrong. 我试图从magaplaza hello world教程制作我的模块,但出了点问题。 I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. 我从github导入了这个模块的代码https://github.com/astorm/magento2-hello-world并且它有效。 from that module, i created it a categories subcategories ajax select drop downs Module. 从该模块,我创建了一个类别子类别ajax选择下拉模块。 After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. 在magento2安装的aap / code目录中安装后,请按照以下URL ... http://www.example.com/hello_mvvm/hello/world您可以从这里下载其代码https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns并将其放在您的aap / code文件夹中。 than run these commands... 比运行这些命令...

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检查模块功能


I've been wrestling with Magento for the last month or so and I'm still trying to figure it out. 我在上个月左右一直和Magento搏斗,我还在努力解决这个问题。 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. 新的付款方式令人大开眼界。

For debugging I'd definitely recommend using FirePHP and looking at your HTML source when something goes wrong. 对于调试,我肯定建议使用FirePHP并在出现问题时查看HTML源代码。 The ole echo debug method doesn't really work all that well. 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. Magento使用由XML组成的配置文件来决定它需要做什么。 In order to get it to run your own stuff as opposed to core functionality you need the correct xml. 为了让它运行你自己的东西而不是核心功能,你需要正确的xml。 Unfortunately there is no guide on how to build you XML; 遗憾的是,没有关于如何构建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 uses methods like Mage::getModel('mymodel') , Mage::getSingleton('mysingleton') , Mage::helper('myhelper') to return objects of certain classes. Magento使用Mage::getModel('mymodel')Mage::getSingleton('mysingleton')Mage::helper('myhelper')方法返回某些类的对象。 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.xml file. 如果您希望它使用您自己的,您需要在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 . Magento中的很多对象最终扩展了一个名为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. 例如,您将看到它用作一个美化数组,用于将数据从一个方法传递到另一个方法。

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 $this being used a lot. 你会看到$this被大量使用。 It means a different class depending on what file you see it. 它意味着一个不同的类,具体取决于您看到的文件。 get_class($this) is your friend, especially in conjunction with FirePHP. 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. Magento喜欢OO。 Don't be surprised if tracing a method takes you through 5-10 different classes. 如果跟踪方法会带您通过5-10个不同的类,请不要感到惊讶。

Read the designer's guide here . 这里阅读设计师指南。 It's meant mostly for graphics designers, but you need it 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. 还有更多,但在此变成论文之前我会停在这里。


First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect . 首先,我强烈建议您从PHP Architect购买PDF /电子书 It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. 这是20美元,但是我能找到的唯一直截了当的“Magento如何工作”资源。 I've also started writing Magento tutorials at my own website . 我也开始在自己的网站上编写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 and Java), pick another cart . 其次,如果您有选择,并且不是经验丰富的程序员或无法访问有经验的程序员(理想情况下是PHP Java),请选择另一个购物车 Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. Magento设计精良,但它被设计成一个购物车解决方案,其他程序员可以在其上构建模块。 It was not engineered to be easily understood by people who are smart, but aren't programmers. 它的设计并不容易被聪明的人理解,但不是程序员。

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. 第三,Magento MVC与Ruby on RailsDjangoCodeIgniterCakePHP等有很大不同.MVC模型最近受到PHP开发人员的欢迎。 I think it's based on the Zend model, and the whole thing is very Java OOP-like. 我认为它基于Zend模型,整个事情就像Java OOP一样。 There's two controllers you need to be concerned about. 你需要关注两个控制器。 The module/frontName controller, and then the MVC controller. 模块/ 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. 第四,Magento应用程序本身是使用您将使用的相同模块系统构建的,因此探索核心代码是一种有用的学习策略。 Also, a lot of what you'll be doing with Magento is overriding existing classes. 此外,您将使用Magento做的很多事情都会覆盖现有的课程。 What I'm covering here is creating new functionality, not overriding. 我在这里介绍的是创建新功能,而不是覆盖。 Keep this in mind when you're looking at the code samples out there. 当你在那里查看代码样本时,请记住这一点。

I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. 我将从您的第一个问题开始,向您展示如何设置控制器/路由器以响应特定的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. 但是,我将简要地谈谈您的SQL问题。

Magento uses an EAV database architecture. Magento使用EAV数据库架构。 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. 我知道它在SQL表中都存在,但最好不要考虑使用原始SQL查询来获取数据,否则你会发疯。

Final disclaimer. 最后的免责声明。 I've been using Magento for about two or three weeks, so caveat emptor. 我已经使用Magento大约两三个星期了,所以请注意。 This is an exercise to get this straight in my head as much as it is to help Stack Overflow. 这是一个练习,可以直接解决这个问题,就像帮助Stack Overflow一样。

Create a module 创建一个模块

All additions and customizations to Magento are done through modules. Magento的所有添加和自定义都是通过模块完成的。 So, the first thing you'll need to do is create a new module. 因此,您需要做的第一件事是创建一个新模块。 Create an XML file in app/modules named as follows app/modules创建一个XML文件,命名如下

cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml
<?xml version="1.0"?>

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. MyCompanyName是您修改的唯一命名空间,它不一定是您公司的名称,而是推荐的约定my magento。 HelloWorld is the name of your module. 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). 现在模块文件到位了,我们需要让Magento了解它(并检查我们的工作)。 In the admin application 在管理应用程序中

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

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" 在“禁用模块输出”设置框中,查找名为“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"?>

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


So, in your configuration file, add the following section. 因此,在配置文件中,添加以下部分。

<!-- ... -->
            <!-- the <helloworld> tagname appears to be arbitrary, but by
            convention is should match the frontName tag below-->
<!-- ... -->

What you're saying here is "any URL with the frontName of helloworld ... 你在这里说的是“任何带有helloworld的frontName的URL ......


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. 因此,通过上述配置,当您加载上面的helloworld页面时,您将获得404页面。 That's because we haven't created a file for our controller. 那是因为我们还没有为控制器创建文件。 Let's do that now. 我们现在就这样做。

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 而不是404,你将获得PHP / Magento异常

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. 类的名称需要基于您在路由器中提供的名称。

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. 我们刚刚设置的是模块/ frontName控制器。 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 如果你想添加控制器或动作,你必须记住,Magento URL的树的第一部分是不可变的,它们将始终采用这种方式http://example.com/magento/index.php/frontName/controllerName/actionName

So if you want to match this url 所以,如果你想匹配这个网址


You will have to have a FooController, which you can do this way : 你必须有一个FooController,你可以这样做:

touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.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. 请注意,默认控制器IndexController和默认操作indexAction可以隐式但必须是显式的,如果它后面的东西。 So http://example.com/magento/index.php/helloworld/foo will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. 所以http://example.com/magento/index.php/helloworld/foo将匹配控制器FooController和动作indexAction而不是IndexController的动作fooAction。 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/foo because the second part of the url is and will always be the controllerName. 如果你想拥有一个fooAction,在控制器IndexController中你必须像这样明确地调用这个控制器: http://example.com/magento/index.php/helloworld/index/foohttp://example.com/magento/index.php/helloworld/index/foo因为url的第二部分是和将永远是controllerName。 This behaviour is an inheritance of the Zend Framework bundled in Magento. 此行为是Magento中捆绑的Zend Framework的继承。

You should now be able to hit the following URLs and see the results of your echo statements 您现在应该能够点击以下URL并查看echo语句的结果


So, that should give you a basic idea on how Magento dispatches to a controller. 所以,这应该给你一个关于Magento如何调度到控制器的基本想法。 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控制器类中查看模型和模板/布局系统的使用方法。

  • 0
  • 0
    觉得还不错? 一键收藏
  • 0


  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助




当前余额3.43前往充值 >
领取后你会自动成为博主和红包主的粉丝 规则
钱包余额 0