Magento Introductory Development Tutorial

Source: Internet
Author: User

modules-> Module

controller-> Controller

model-> Model

Magento is the most powerful shopping cart online platform on the planet. Of course, you should have no doubt about it. However, you may not yet know that Magento is also an object-oriented PHP framework. You can develop dynamic Web applications with the powerful features of the Magento Shopping cart program.

This is the beginning of the Magento Chinese Development Manual, and we will cover most of the Magento development framework features throughout the manual. Don't try to grasp all the features in this article right away. It's just a start, but it's enough to make you stand out from your peers.

In this article, you will learn:

    • Magento module (Magento Modules) Code organization
    • Configuration-based MVC architecture
    • Magento controller (Magento Controllers)
    • URI-based model instantiation (context-based URI model Loading)
    • Magento model (Magento Models)
    • Magento Assistant (Magento Helpers)
    • Magento layout (Magento Layouts)
    • Event Monitoring (observers)
    • Magento class rewrite (class Overrides)
    • Summarize

Before you begin, you can try to see a graphical visual representation of the Magento MVC pattern. Magento_mvc.pdf

Code organization in the Magento module

Magento is organized by putting code in a separate module. In a typical PHP MVC application, all the controllers are placed in a folder, all the models are placed in a different folder, and so on. In Magento, the files are grouped based on functions, and this block of code is called a module.

Magento's code:

For example, if you are looking for Magento in the payment function, you just need to find the folder in the code below, you can get all the controller, model, assistant, blocks and so on.

App/code/core/mage/checkout

If you want to find out about Google Checkout in Magento, you just need to find the following folder to get all the information you want.

App/code/core/mage/googlecheckout

Your code:

If you want to extend Magento, do not take it for granted to modify the files in the core folder, and do not put your own controller, model, assistant or blocks in the core folder. All extensions for Magento will be made in the local folder.

App/code/local/<package>/<modulename>

The package (also known as the namespace, which is not the namespace mentioned in the PHP manual) is the only name that identifies your company, organization, or individual through the package. With the package, Magento communities around the world can use their own package names when creating module extensions to avoid naming conflicts with other developers.

When creating a new module, you need to tell Magento about the new module. You can add an XML file in the following directory.

App/etc/modules

There are two types of XML files in this directory, the first of which is to open a separate module, named in the following way:

Packagename_modulename.xml

The second file is used to open multiple modules from a package, named in the following ways:

Packagename_all.xml

Configuration-based MVC system

Magento is a configuration-type MVC (configuration-based MVC) system. Another MVC system is the one used by most PHP frameworks, the contractual MVC (convertion-based MVC).

In an agreed-upon MVC system, if you add a controller, or a model, you just need to create the file and the class according to the agreed content, and the system will automatically recognize it.

In the configuration-type MVC system, such as Magento, in addition to the need to add the corresponding files and classes, but also need to explicitly tell the system that the existence of the class. In the Magento, each module has a. config file. This file contains a module-related configuration information. At runtime, the configuration files for all modules are loaded into a huge configuration file tree (The following article describes how to view this configuration tree).

For example, you want to use the model in a module. You need to add code like the following to tell Magento that you will use this model in this module.

<models>

<packagename>

<class>Packagename_Modulename_Model</class>

</packagename>

<models>

Of course, this configuration is not limited to the model, for controllers, assistants, Blocks, routes, event handlers, etc., need to be configured in the module's config.

Magento controller (Magento Controllers)

In any PHP system, the core file must be a PHP file. Magento is no exception, index.php is the core document of Magento.

However, never edit any code in the index.php. In the MVC system, the index.php about the following:

    • Detects the URL address.
    • Distributes the URL addresses of the access to methods in the controller class according to the routing rules.
    • Initialize the controller and invoke the appropriate action method. This step is called distribution. Dispatching.

This means that each valid entry point of Magento (or any MVC system) is a method in the controller file. Take a look at the following URL:

Http://example.com/catalog/category/view/id/25

The URL address after the above domain name can be split into the following sections.

Front Name–catalog

The first part of the URL is known as front Name. It is used to indicate in which module the Magento should look for the controller in the URL. In this example, the catalog is the front Name, which corresponds to the catalog module.

Controller name–category

The second part indicates that the Magento should match the controller. Each module that owns the controller contains a ' controllers ' folder that holds all the controllers under the module. The above URL address, matching the following controller file.

app/code/core/mage/catalog/controllers/categorycontroller.php

The class definition format is approximately:

classMage_Catalog_CategoryController extends Mage_Core_Controller_Front_Action

{

}

In Magento, all controllers inherit from the Mage_core_controller_front_action class.

Action Name–view

The third part is the name of an action method. In this URL, view is the name of an action method.

classMage_Catalog_CategoryController extends Mage_Core_Controller_Front_Action {

publicfunction viewAction() {

}

}

PARAMATER/VALUE–ID/25

Any path that is located after the action method name is considered to be a get variable passed in key/value form. So in our example, ' id/25′ ' represents a variable with a value of 25 for the $_get[' ID '].

As mentioned earlier, if you want a custom module to use a controller, you must configure it. The following is the code that opens the controller in the module.

<frontend>

<routers>

<catalog>

<use>standard</use>

<args>

<module>Mage_Catalog</module>

<frontName>catalog</frontName>

</args>

</catalog>

</routers>

</frontend>

It's not clear what the above is all about, but note <frontName>catalog</frontName>. This is used to correlate modules with URL addresses in Frontname. The Magento core code chooses to match the name of a module to Frontname, but this is not mandatory.

Multiple routers

The routing rules mentioned above are mainly for the Magento shopping cart program (i.e. the front end you can see). If Magento does not match to the correct controller/action in the URL, it tries to use another routine by the rule for the Admin program (background management side). If it still does not match correctly, it will use a special controller Mage_cms_indexcontroller.

The CMS controller checks to see if any content in the Magento Content management system needs to be output, and if there is a content output, reads the content and outputs 404 pages If it is not found.

For example, the default home page for Magento is using a CMS controller.

context-based URI Model Read

So far, we've set up a controller and a method to instantiate a class and do something about it. Magento provides a special way to instantiate models, assistants, and blocks, which are static factory methods that are provided using Mage global classes. For example

Mage::getModel(‘catalog/product‘);

Mage::helper(‘catalog/product‘);

The ' catalog/product ' string is called grouped Class Name. Usually called a URI. The first part of grouped class name is used to indicate which module the class exists in. The second section is used to determine which class will be called.

So, in the example above, ' catalog ' corresponds to the App/code/core/mage/catalog module, which means that our class name begins with Mage_catalog and then adds the product class name to the last part based on the type of call. That

Mage::getModel(‘catalog/product‘);

Mage_Catalog_Model_Product;

Mage::helper(‘catalog/product‘);

Mage_Catalog_Helper_Product;

Magento model

Like most frameworks today, Magento also provides ORM support. ORM allows you to focus on data, not endless SQL statements. For example

$model= Mage::getModel(‘catalog/product‘)->load(27);

$price= $model->getPrice();

$price+= 5;

$model->setPrice($price)->setSku(‘SK1231414‘);

$model->save();

In the above example, we call the "GetPrice" and "Setprice" methods. However, there is no such method in the Mage_catalog_model_product class. So why is the above example able to use these methods? Because the Magento ORM system uses PHP's _get and _set magic methods.

Calling $product->getprice () gets the model property price, and calling $product->setprice () sets the Price property. Of course, all of these assume that model classes do not have GetPrice and Setprice methods. If they exist in the model class, the PHP Magic method is ignored. If you are interested in knowing how this is implemented, you can refer to the Varien_object class, which all of the model classes inherit from.

If you want to get all the data in the model, you can call the $product->getdata () method directly, which returns an array containing all the fields.

You may have noticed that the method in the previous example is in the form of a symbolic link, which is used:

$model->setprice ($price)->setsku (' sk12312542′);

The most important reason to be able to invoke a method in this way is that all the set methods return an instance of the model. you will often see the form of such calling methods in the core code of Magento.

Magento's ORM system also includes a way to query multiple objects through the collections interface. The next meeting reads all of the $5 products in the system.

$product_collection= Mage::getModel(‘catalog/product‘)

->getCollection()

->addAttributeToSelect(‘*‘)

->addFieldToFilter(‘price‘,‘5.00‘);

Here again we see the form of the link invocation method. Collections use of the PHP standard Library to implement Objects that has an array like properties. (This sentence goes beyond the scope of comprehension).

foreach($products_collectionas $product)

{

echo$product->getName();

}

In one of the examples above, you may have noticed the Addattributetoselect method. This method is mentioned separately because it represents a category in the Magento model. Magento has two types of model objects. One is the traditional "one object, one table" active record model. When you instantiate these models, all of the properties are automatically selected.

The second model in Magento is called the entity Attribute Value (EAV) model. This model will distribute the data in different tables in the database according to certain rules. The advanced features of the EAV model allow Magento to change the database model without adding a product attribute (the General shopping cart system has two ways of adding new properties, one is to add database fields and one to use reserved empty fields.) ), thus ensuring a high degree of scalability of the Magento system. When you create a collection for a EAV model, Magento conservative the number of fields it will query, all you can use Addattributetoselect to make the columns you want to get, or use Addattributetoselect (*) to get all the columns.

Magento Helpers Assistant

Magento's helper class contains a series of practical methods that allow you to perform routine operations on objects and variables. For example

$helper= Mage::helper(‘catalog‘);

Did you notice that the second part of grouped Class name was discarded here? Each module has a default data helper class. The following statement is the same as above, that is, the data helper class under the module is used by default.

$helper= Mage::helper(‘catalog/data‘);

Most of the helper classes inherit from Mage_core_helper_abstract, which provides many ways to use them by default.

$translated_output= $helper->__(‘Magento is Great‘);

if($helper->isModuleOutputEnabled()) {

}

Magento layout Layouts

So far, we've introduced controllers, models, and assistants. In a typical PHP MVC system, after operating the model, it is generally

    • Pass the variable into the view.
    • The default outer layout is automatically read by the system
    • The view is then read into the outer layout

However, if you look closely at the Magento controller action method, you will not see these steps,

publicfunction galleryAction() {

if(!$this->_initProduct()) {

if(isset($_GET[‘store‘]) && !$this->getResponse()->isRedirect()) {

$this->redirect(‘‘);

} elseif(!$this->getResponse()->isRedirect()) {

$this->_forward(‘noRoute‘);

}

return;

}

$this->loadLayout();

$this->renderLayout();

}

Unlike the typical PHP MVC form, the controller action method ends with a two output layout method. So, the V view part of the Magento MVC system may be quite different from what you often use. Because, you have to explicitly output the layout in the controller.

Also, the layout of Magento itself differs from the MVC system that you often use. The Magento layout is an object that contains nested or tree-like block objects. Each block object outputs part of the HTML, and the output HTML consists of two parts, a block of PHP code, and a. phtml template file.

The blocks object is responsible for interacting with the Magento system and fetching data from the model, while the phtml template file generates the necessary HTML code for the page.

For example, the page header Block file app/code/core/mage/page/block/html/head.php uses its corresponding page/html/head.phtml template file.

In other words, the blocks class is like a mini controller, and the. phtml file is the view file.

The default, when you call,

$this->loadLayout();

$this->renderLayout();

Magento will load up a layout with a skeleton site structure (this paragraph can be understood, but not surprisingly the best translation, probably meaning that Magento would read the site's layout framework). These structures are blocks used to output head,body and to set the layout of the order bar or multiple columns. In addition, there are some content blocks responsible for the actual output like navigation, product classification and so on.

The "Structure" and "content" blocks are arbitrarily set in the layout system. It is not common to intentionally add code in the code to differentiate whether a block is structure or content, but blocks is either "structure" or "content".

In order to add a content blocks to the layout, you need to tell the Magento system

"Magento, just add these blocks to the content block."

Or

"Magento, put a couple of blocks in the" left column "structure block.

These can be controlled by the code in the controller,

publicfunction indexAction() {

$block= $this->getLayout()->createBlock(‘adminhtml/system_account_edit‘);

$this->getLayout()->getBlock(‘content‘)->append($block);

}

But the more common way (at least in the foreground shopping cart app) is to use an XML file-based layout system.

In one style, the XML-based layout allows you to delete the Blocks of the normal output or add the default skeleton area (that is, structure Blocks). For example, the following XML layout file,

<catalog_category_default>

<referencename="left">

<blocktype="catalog/navigation" name="catalog.leftnav" after="currency" template="catalog/navigation/left.phtml" />

</reference>

</catalog_category_default>

The function of the above code is to insert the catalog/navigation block into the left column structure block in the default action method of the category controller of the catalog module, and use the catalog/navigation/ left.phtml template file.

There is one more important feature about blocks. In the template file, you will see a lot of code similar to the following,

1

$this->getChildHtml(‘order_items‘)

This is how blocks are nested in block output. However, the template file for the child block can be called through the getchildhtml () method in the template file only if it is explicitly declared in the XML layout file that a block contains another child block.

For example, in an XML layout file,

<catalog_category_default>

<referencename="left">

<blocktype="catalog/navigation" name="catalog.leftnav" after="currency" template="catalog/navigation/left.phtml">

<blocktype="core/template" name="foobar" template="foo/baz/bar.phtml" />

</block>

</reference>

</catalog_category_default>

Then from Catalog/navigation block, we can call $this->getchildhtml (' Foobar ');

Observers observer

Like many excellent object-oriented systems, Magento provides the user with a hook by implementing the Observer pattern. Magento generates an event signal for a specific action method called on a page request (model store, user login, and so on).

When you create a new module, you can "listen" for these events. For example, you want to send an e-mail to the administrator's mailbox when a particular user logs in to the store, which can be done by "listening" to the Customer_login event.

<events>

<customer_login>

<observers>

<unique_name>

<type>singleton</type>

<class>mymodule/observer</class>

<method>iSpyWithMyLittleEye</method>

</unique_name>

</observers>

</customer_login>

</events>

Next is the code that should run when the user logs on:

classPackagename_Mymodule_Model_Observer

{

publicfunction iSpyWithMyLittleEye($observer)

{

$data= $observer->getData();

//code to check observer data for out user,

//and take some action goes here

}

}

Replication of Class Overrides classes

Finally, the Magento system also provides the replication functionality of the class, and you can overwrite the model, helper, and blocks classes in the core code with your own code.

Here are some examples to help you understand this feature more easily. The model class of the product is mage_catalog_model_product. Whenever the following code is called, a Mage_catalog_model_product object is generated.

1

$product= Mage::getModel(‘catalog/product‘);

This is the factory model. Magento's type of replication system operation mode is probably the case,

"Magento! If a request corresponds to Catalog/product, do not instantiate mage_catalog_model_product, let Packagename_modulename_model_foobazproduct take over "

In the model, the way the class is covered and the naming rules are as follows,

classPackagename_Modulename_Model_Foobazproduct extends Mage_Catalog_Model_Product

{

}

In this way, you can change the behavior of the methods in the parent class and fully inherit all the functionality of the parent class.

classPackagename_Modulename_Model_Foobazproduct extends Mage_Catalog_Model_Product

{

publicfunction validate() {

//添加一些自定义的验证功能

return$this;

}

As previously mentioned, replication also needs to be configured in the config configuration file.

<models>

<!-- tells the system this module has models -->

<modulename>

<class>Packagename_Modulename_Model</class>

</modulename>

<!-- does the override for catalog/product-->

<catalog>

<rewrite>

<product>Packagename_Modulename_Model_Foobazproduct</product>

</rewrite>

</catalog>

</models>

Magento Introductory Development Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.