magento – instantiation abstraction and Autoload

  • magento autoload
  • magentos autoload functionality

If you Aore at all familiar with object-oriented programming, the following line should you look for familiar.

$customer_group = new Mage_Customer_Model_Group();

We, Aore instantiating an instance of the class Mage_Customer_Model_Group. However, if you were looking at the code base for Magento Mage_Customer_Model_Group you, AOD never a single expression that everything looks as above. They would, however, see a lot of code that looks something like this

$customer_group = Mage::getModel('customer/address');

By the end of this article, you understand, all how and why the instantiation of classes in Magento, and how to include custom models and assistants and blocks into their own modules.

PHP Autoload

Before we get into the Nitty Gritty of Magento, AOS class instantiation abstraction, we need to talk to spend a minute or two PHP include files to get.

Prior to version 5, PHP did not, AOT provide much guidance on how project files should be structured. PHP is a simple concept, including the requirement or a file. You will pass include the testimony and require a string that contains a path to another PHP file

include('/path/to/file.php');

PHP and acts as if you had the code in file.php part of your main program. There, AOS no automatic namespaces, linking, packaging or any attempt to reconcile the context to the files in it.

Over the years, this business and any PHP project to their own conventions, as their base system / library code should be added the development led. When two unconventional developers a difference of opinion on how this should be attained, the resulting code base is quickly a rat nest of AOS includes redundant and requires.

While PHP doesn still aot enforce a particular strategy, PHP 5 introduces the concept of Autoloading your class files. Developers can autoload the function that is called when an undefined class is referenced throughout the code base to create a single argument in the referenced class name.

For example, consider the following simple function autoload

function __autoload($class_name){
    require('lib/'.strToLower($class_name).'.class.php');
}

The team, which this function stores all of his classes used in a directory structure that looks something like this

lib/customer.class.php
lib/email.class.php

Although not for every project when the autoload sensible approach uses free care with developers about when and where they and their class files, and the enforcement / promotion of a consistent naming convention.

Magento Autoload

As you would imagine, Magento module system uses the function autoload difficult. While tricky to master if you understand the naming convention, you know exactly where to find it is Magento each class, and to know where your own classes instead.

You can split all Magento classes in four parts that we mention namespace, module name, class type and name. Consider the above The-class

Mage_Customer_Model_Group
Namespace_ModuleName_ClassType_Name

Name Space
A-class’s namespace, you can know who is responsible for the creation and maintenance of the class, and helps prevent name collisions between modules. All Magento Core modules use the Mage namespace, and the recommended convention is to use a version of the name of your company for your own modules.
Module Name
All customization of Magento is done by modules that a collection of source code and configuration files that can be loaded into the Magento system. In the above example, the client module name.
Class Type
Without too much detail, there are several large groups of classes in Magento, including model, Singleton, helpers and block.
Name
Finally, each class should have a unique name that describes the intended use or function. In the above example is of this group.

Directory Structure

PHP source files for the modules are stored in the App folder. Magento Core files are stored separately from local files

//base for core files
app/code/core

//base for your custom and downloaded modules
app/code/local

There is also a folder named Legacy community. Can you ignore this folder. Varian’s current recommendation is that all non-core modules are stored in the local folder.

Sun Magento uses autoload to determine the above parts, where to find the source of a certain class. Starting with the appropriate base folder, find the source code to the file on

Namespace/ModuleName/ClassType/Name.php

Thus, the class Mage_Customer_Model_Group be found in the following folder

app/code/core/Mage/Customer/Model/Group.php

A custom class called Companyname_RoiMagic_Helper_Moneymaker would be found in

app/code/local/Companyname/RoiMagic/Helper/Moneymaker.php

So, you may be wondering what to do with a class like this

Mage_Customer_Model_Address_Config

Magento separates the name of the class in the same sections are such that the class name is “as Address_Config. However, you will not find this class at the following location

//not here
app/code/core/Mage/Customer/Model/Address_Config.php

Instead, stresses in a name to say Magento on the search for the class, in subdirectories, that you would find this source file

app/code/core/Mage/Customer/Model/Address/Config.php

Abstracting Away Class Instantiation

So we now know the basic naming convention for a Magento class, but we are still left with this mystery

$customer_group = Mage::getModel('customer/address');

It is always important to remember that Magneto is more than one application, it is a programmatic system. However, if you created a new system, engineers are always too abstract to find things. With Magento, Varian engineers have abstracted away the declaration of classes in a series of static “get” method on the global Mage object.

The line of code above is to say, in force

Give me an instance of the model address the concept of a customer’s address

Let the word concept percolate in the back of your brain a bit, because we have to detour to another, this time in the world of the config files

Magento Config Files

Each module has a file called config.xml Magento, etc in the module folder. When the system loads a Magento request, all of these config files are involved in a large XML structure.

If you call the various Mage: getSingleton getModel, Mage:: Mage:: getBlockSingleton or Mage:: getHelper, tell Magento

“Hey, look in your config tree and tell me what class I should be URI for this instantiation”

The URI is the path string, as you are by these methods. Consider calling the following method and config fragment.

$customer_group = Mage::getModel('customer/address' )
<config>
    <!-- ... -->
    <global>
        <models>
            <customer>
                <class>Mage_Customer_Model</class>
                <resourceModel>customer_entity</resourceModel>
            </customer>
            <!-- ... -->
        </models>
    </global>
    <!-- ... -->
</config>   

When calling getModel, you tell Magento into view globals / models section of the configuration file. Then tell the first section of the URI Magento which it should <models> among us children. In this case the customer (customer / address). The <class> node then give us the basis for the names of our class.

The second part of the URI is used to complete the name of the class. In this example, it is not used to rewrite something to look up in the XML configuration file (see below for an example where the opposite is true). So in our example that the address (customer / address), so we have a final class name

Mage_Customer_Model_Address

Here is another example. Consider the following call getModel

Mage::getModel('dataflow/batch_export')

We look to the <models> block our merged config called for a node data flow, and we find

<dataflow>
    <class>Mage_Dataflow_Model</class>
    <resourceModel>dataflow_mysql4</resourceModel>
</dataflow>

This gives us a base class name Mage_Dataflow_Model what we will connect with the second part of the URI to a final name of the class

Mage_Dataflow_Model_Batch_Export

With your Own Modules

So far we have only used getModel Mage to the core modules. However, the same concept applies to your own modules, so most Magento tutorials you recommend a standard setup <models>, <blocks> and <helpers> section

The following module config

<global>
    <models>
        <roimagic>
            <class>Companyname_RoiMagic_Model</class>
        </roimagic>
    </models>
</global>

It would make it an instance instantiated with Company_Roimagic_Model_Spam

Mage::getModel('roimagic/spam');

High Concept

So, this is a lot to take in. This last piece is the spirit of bending of the lot, and makes worthwhile the part of all these efforts. Previously we talked about the concept of a customer’s address. With regular class instantiation abstracted away, we are now free to override (if you went to college before 1999) or monkey-patch (if you went to college after 1999) the system Magento.

Overriding base-class Magento is one of the most important methods expand Magento. Magento during an event is for you, hook in, there is no way to Varian engineers know which events you may need.

By building a mechanism other than force in their system, there is no part of Magento’s model, helper or blocks that can not change when you require.

Consider the Magento Shopping Cart Class

//getSingleton is identical to getModel, except it ensures only
//one instance of the class is ever created.  i.e. any Magento model
//may be treated as a singleton
class Mage_Checkout_Model_Cart
$cart = Mage::getSingleton('checkout/cart');

Magento is a basic idea of what a car, but your approach might be different. Let’s say that the people we are expanding our RoiMagic module are paranoid about the people for change their minds so that they are to each item that is removed from the basket are logged.

The shopping cart model has a method called removeItem. What we set out to do

1st

Create a new model that will expand the Mage_Checkout_Model_Cart class, but define the removeItem method for our customers include logic (while maintaining previous behavior)
2nd

Tell Magento we want the customer-standard model with our own override

So, first thing we will do, create a file and stub for our new class called Companyname_RoiMagic_Model_Cart

touch app/code/local/Companyname/RoiMagic/Models/Cart.php
 #paste the following code inside Cart.php
class Companyname_RoiMagic_Model_Cart extends Mage_Checkout_Model_Cart{}

Next, we are the new method to add our class. This is standard class inheritance at work.

class Companyname_RoiMagic_Model_Cart extends Mage_Checkout_Model_Cart{
    public function removeItem($itemId){
        Mage::Log('Item '.$itemId.' was removed from the cart');
        return parent::removeItem($itemId);
    }
}

Let us consider again the results of a call to our parent company. This past record can completely unchanged, but we can throw some additional logging. As a general rule, unless you are familiar with the behavior of the Magento system, you should always try to keep the default behavior back to the method of the parent company.

So, with our new class in place, the final step is to say, Magento to use our class. To receive as a Magento module, an instance of the cart, the call is that the used

Mage::getSingleton('checkout/cart');

As a reminder, the method getSingleton identical to the getModel method, except that Magento will be the model instantiated once and then cache the results for later retrieval. What we are concerned about here in the URI of the checkout / cart. This means Magento will be merged into the config on the search for a node

<global>
    <models>
        <checkout>
            <!-- ... -->

So, as part of our module config, we want a part that contains our checkout rewrite rule to add

<global>
    <models>
        <!-- standard model section -->
        <roimagic>
            <class>Companyname_RoiMagic_Model</class>
        </roimagic>
        <!-- new checkout section -->
        <checkout>
            <rewrite>
                <cart>Companyname_RoiMagic_Model_Cart</cart>
            </rewrite>
        </checkout>
    </models>
</global>

Thus, the node <checkout> the name of the Magento core module we have overriding, you or the first part of the URI of the call for Mage:: getSingleton (‘checkout / cart’).

The nodes can <Rewrite> Magento we want to know something in the default customer module override. Remember Magento connects together all the configuration files, see it more like

<checkout>
    <class>Mage_Checkout_Model</class>
    <resourceModel>checkout_mysql4</resourceModel>
    <rewrite>
        <cart>Companyname_RoiMagic_Model_Cart</cart>
    </rewrite>
</checkout>

The presence of the nodes can <Rewrite> Magento know it should not assume the desired class Mage_Checkout_Model_Cart. First, it provides the second part of the URI Mage:: getSingleton (Checkout / Cart “) and looks for a node with that name in the <Rewrite> section. If it finds one, the value found there used to instantiate the class. In this case, that is Companyname_RoiMagic_Model_Cart

Wrap-up

Magento is hard but not impossible. Most of the difficulty comes from the absence of key documentation and a wealth of “Give a man a fish” style tutorials. As arbitrary and illogical, as many of the rules seem, there is a logic and a design to the system. If you understand that logic, you will have one of the customizable, powerful e-commerce systems at your service.

(Based on Alanstorm Turtorial)

This is the best product I have bought! They have really helped my erection. Cialis online fast delivery! Our goal is to provide medications at discount rates to everyone who is affected by expensive local prices.

Comments

Leave a Reply

Your email address will not be published.

twenty + nine =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Security Code: