Create an extension for Magento

Create an extension for Magento

magento

When we talk of CMS prepared to shops, we come to a head, usually two names: Magento andPrestaShop . Like most CMS, you can expand its functions by using extensions or modules. The case before us is the same, that of creating extensions for Magento .

Through this tutorial, learn the basics of creating modules for Magento: directory structure, observers, models and some basic tricks. This tutorial is the same as the guys offer Smashing Magazine , you can check the original English if you want. We will explain it in Spanish.

The tutorial consists of a module that monitors the changes made in the products (to add or change).

Before you start …

We assume that you have a Magento store up and running, and obviously, you’re the manager of the store.No matter what version of Magento have, either pay or free, and we’re playing very basic aspects that do not change from one to another. We also assume that you have knowledge in PHP and XML.

Disabling the cache

First things first: Disable Magento cache options. ‘s cache is the enemy number one developer of Magento. If we do not, we run the risk of being left for hours stuck at one point, waiting for Magento refresh your cache … once a day. To do this, we’ll System > Cache Manager , click on » Select All «in the table above to the left, and the right is a dropdown where you select» Disable «. Press » Send «. Ready, cache disabled, is a very important step.

The directory structure

Magento keeps its modules in the folder app / code . This folder is structured as follows:

  • / Core : In this folder are the system modules . Is its core. So, unless we want to destroy our Magento (there are people for everything), playing here is a mortal sin . Magento is prepared to accept changes to these modules directly without editing, so that if there is an error, the original code remains.Of course, it is good practice to read the contents of this folder if you want to see examples of how modules work, but without touching anything. was look, but not touch.
  • / Community : Here live the modules developed by other companies outside the organization of Magento. For example, applications installed through Magento Connect will stop here.
  • / Local : If this folder does not exist on your system, by the power that has been given me in writing this blog, I give you permission to create it. Usually, when installing Magento creates this empty folder (or does not create). This is where we are going to develop our module. Folder is to develop in our system without our extension we mix with the rest and we can find it quickly. Work here for the rest of the tutorial.

A module structure

Now that we know where we will work, we need to know how to structure a module. Magento works in a very well organized by folders, then XML will recognize if the code is well written. For starters, let’s get intoapp / code / local .

Namespace

In app / code / local ‘ll create a folder. Usually, this folder should be called as our organization , and acts as a namespace (namespace, we will serve to distinguish the extensions that we developed ). Thus, the plugins are in the folder magento Mage , for example. We’ll create the folder Codigonexo (you can call it whatever you want). Currently, our path is app / code / local / Codigonexo . You can give it any name you want, but only letters: no space, no underscores (this is important, underscores then be used for other purposes , so here we can not use them). Ah, the system is case sensitive , so after these names must be respected, except where indicated otherwise.

Module Name

Inside the folder with our company, we will create another folder, whose name is the module name . A good practice is to use descriptive names . As in this case we will monitor changes made ​​to products, a good name would be: ControlDeProductos . As before, no spaces or underscores, and case sensitive .

Our route now is app / code / local / Codigonexo / ControlDeProductos .

Module Configuration

Let’s now create the configuration file of the module, which will give the module version and contain observers. Within ControlDeProductos, create the folder etc , and within this, the file config.xml . This file will contain the following code:

<?xml version="1.0" encoding="UTF-8"?>

<!-- Nodo principal de la configuración de un módulo de Magento -->

<config>

	<!-- El nodo module contiene información básica sobre cada módulo de Magento -->
	<modules>

		<!-- 
			Esto debe coincidir exactamente con el nombre del namespace y el nombre del módulo,
			es decir, con la carpeta que contiene al módulo y la carpeta del módulo, separadas con un guion bajo
		-->
		<Codigonexo_ControlDeProductos>

			<!-- La versión del módulo. Empezamos en 0.0.1 -->
			<version>0.0.1</version>

		</Codigonexo_ControlDeProductos>

	</modules>

</config>

No need to explain much more, right? It’s all in the code comments.

Activating our module

The next step will tell Magento which has a new module and active in the local folder and you should get to read its configuration. This time, let’s go back to the app folder. Navigate to app / etc / modules , and create a new file, named with the name of the namespace and module:Codigonexo_ControlDeProductos.xml in our case.

<?xml version="1.0" encoding="UTF-8"?>

<config>

	<modules>

		<Codigonexo_ControlDeProductos>

			<!-- Indica si nuestro modulo está activo: true o false -->
			<active>true</active>

			<!-- Indica en qué directorio encontrará el módulo: core, community o local -->
			<codePool>local</codePool>

		</Codigonexo_ControlDeProductos>

	</modules>

</config>

 

Check: Is the active module?

Now, with what we have done, we have a module running on Magento. It does nothing, okay, but is working, and should recognize Magento . For this, we Magento administrator and click in System >Settings in the left menu enter Advanced (the bottom, in subsection «Advanced», the last). We will get a page with a link » Disable Modules Output «. By clicking on the link will display the list of modules.

If we have done all the above steps correctly, our module should be listed here. If not, then review the tutorial right here, look at every point, every comma, every underscore, each question mark. This is usually the time when developers discovered the aforementioned cache of Magento …

So far, our folder structure is as follows:

app
|- code
|  |- local
|     |- Codigonexo
|        |- ControlDeProductos
|           |- etc
|              |- config.xml
|
|- etc
|  |- modules
|     |- Codigonexo_ControlDeProductos.xml

Defining an observer

Observers of events are very powerful and are one of the cleanest ways to extend functionality of magento without having to rewrite or overwrite any kernel method or class. As we observe the event is launched right after saving a product, the event code that interests us is catalog_product_save_after .Determine what event code used when defining an observer requires a basic knowledge of the structure of Magento models, which is beyond the scope of this tutorial. But talk about it another time.

Back to our file config.xml and editemoslo a little:

<?xml version="1.0" encoding="UTF-8"?>

<config>
	<modules>
		<Codigonexo_ControlDeProductos>
			<version>0.0.1</version>
		</Codigonexo_ControlDeProductos>
	</modules>

	<!-- Configuramos el comportamiento del módulo dentro de global -->
	<global>

		<!-- Definimos un evento observador -->
		<events>

			<!-- Establecemos el código del evento que queremos observar -->
			<catalog_product_save_after>

				<!-- Aquí definimos el observador del evento -->
				<observers>

					<!--
						Este es el identificador único para el nodo catalog_product_save_after.
						Por convención, se escribe el nombre del módulo en minúsculas.
					-->
					<codigonexo_controldeproductos>

						<!-- El modelo a instanciar-->
						<class>codigonexo_controldeproductos/observer</class>

						<!-- El método de la clase a llamar-->
						<method>control</method>

						<!-- El tipo de clase a instanciar -->
						<type>singleton</type>

					</codigonexo_referals>

				</observers>

			</catalog_product_save_after>

		</events>

	</global>

</config>

 

Setting the models directory

In the event that we have defined, we refer to a model that does not yet exist. We have informed Magento of its existence, adding the following code to config.xml :

<?xml version="1.0" encoding="UTF-8"?>

<config>
	<modules>
		<Codigonexo_ControlDeProductos>
			<version>0.0.1</version>
		</Codigonexo_ControlDeProductos>
	</modules>

	<global>

		<!-- Definimos los modelos -->
		<models>

			<!--
				Identificador único para el nodo de modelos.
				Por convención, se escribe el nombre del módulo en minúsculas.
			-->
			<codigonexo_controldeproductos>

				<!--
					La ruta a nuestro directorio de modelos, separando
					los directorios con guiones bajos
				-->
				<class>Codigonexo_ControlDeProductos_Model</class>

			</codigonexo_controldeproductos>

		</models>

		<events>
			<catalog_product_save_after>
				<observers>
					<codigonexo_controldeproductos>
                                                <class>codigonexo_controldeproductos/observer</class>
                                                <method>control</method>
						<type>singleton</type>
					</codigonexo_controldeproductos>
				</observers>
			</catalog_product_save_after>
		</events>
	</global>
</config>

 

Creating the model of the observer

Now, create the model instantiated when the event is triggered. This is done in app / code / local / Codigonexo / ControlDeProductos / Model / Observer.php (correct, you have to create the folder Modeland the file Observer.php ):

<?php

/**
 * Nuestra clase debe nombrarse siguiendo la estructura de nuestro
 * Observer.php, empezando desde el namespace, separando los directorios
 * con guiones bajos.
 */

class Codigonexo_ControlDeProductos_Model_Observer{
    /**
     * Magento pasa como primer parámetro de los eventos un Varien_Event_Observer
     */
     public function control(Varien_Event_Observer $observer){
         // Recupera el producto que está siendo actualizado desde el evento observador.
         $product = $observer->getEvent()->getProduct();

         // Escribe una nueva linea en var/log/product-updates.log
         $name = $product->getName();
         $sku = $product->getSku();
         Mage::log(
            "{$name} ({$sku}) updated",
            null,
            'product-updates.log'
         );
     }
}

?>

 

That’s it! Let’s try works

First of all, remember that we are using the functions of » logs «of Magento. By default, these options are disabled, so you should check that they are enabled in System > Configuration > Developer (again, bottom), click on » Log Settings «and set» Enabled «to Yes (and finally, click on Save settings ) and check the folder permissions Magento.

Our final structure of folders is this:

app
|- code
|  |- local
|     |- Codigonexo
|        |- ControlDeProductos
|           |- Model
|           |  |- Observer.php
|           |
|           |- etc
|              |- config.xml
|
|- etc
   |- modules
      |- Codigonexo_ControlDeProductos.xml

 

To verify that our module works, we can add a new product or modify an existing one. In the folder var / logfrom our Magento has had to see a file called product-updates.log . If we open it, we will see the changes we have made ​​in our product.

With what we have learned today, we have a basic idea of how Magento works inside . It is a good idea, as I said at first, read how other modules are made ​​for other examples of use of observers and models.

Be sure to read the next part of the tutorial: Add pages from an extension !

«We are drowning in information 
but starved for knowledge » 
– John Naisbitt

¿Te ha gustado el artículo?
Sé el primero en calificar esta publicación.
1 estrella2 estrellas3 estrellas4 estrellas5 estrellas
Loading...

Suscríbete. Déjanos tu email y recibe contenido genial cada mes


Artículo escrito por

¡Exprésate! Dejanos tu comentario

Tu dirección de correo electrónico no será publicada.



Aún no hay comentarios en esta entrada. ¿Te animas?