PHP Community Spirit T-Shirt Design Competition

I entered a design for the PHP Community Spirit T-Shirt Design Competition. And it got approved today. It’s a simple design that uses the PHP logo colors and font. If you like it you can vote for it by following the design below.

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

New elePHPant :)

After purchasing a new batch of the friendly blue guys. Damien Seguy was so friendly to send me an early Christmas present :)

I have some small versions left by the way. So if you are one of those people looking. Drop me a line or leave a comment.

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Returning Blocks from controllers without layout attached in Magento

When working in the admin environment of Magento i had to add a controller action that was called by an Ajax request. The problem however is that all layout data is returned as well when calling

$this->renderLayout();

from the controller. So my next attempt was to try to render the block separately and adding it to the layout.

$this->_initCustomer();
$this->getResponse()->setBody(
            $this->getLayout()->createBlock('block/location')
            ->setCustomerId(Mage::registry('current_customer')->getId())
            ->setData('list', $list)
            ->setUseAjax(true)
            ->toHtml()
);

This kinda worked. But now i had no more control over the template used. Or maybe i missed that part. But i don’t like to specify my Block anyway Magento should pick this up automatically.

Solving this issue is actually quite easy. The only thing we need to do is change the layout structure of the module. We change the name to root. And that’s it!


The name attribute tells Magento it is a root block so no need for the rest of the layout.

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Error’d

I really like the eclipse platform. But yesterday morning it was my own WTF moment when my IDE crashed while building a large project.

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Override controllers in Magento

The last time i had to rewrite one of the core Magento blocks. And that turned out to be quite easy. My new challenge was to rewrite / overwrite one of the Core admin controllers. In this case the Mage_Adminhtml_CustomerController.

I had no idea where to start so i did some googling beforehand. And came to the conclusion that a lot of people are trying to do this. Because of this there is a long list of solutions to solve this. And in most cases developers just advice to drop the Core class in the local folder and work from there. But that doesn’t really make sense. First of all it code duplication in the worst form. And besides that all cool OO stuff like extending is gone.

And since Magento is such a flexible system. There must be a good clean way to solve this. One thread i found had some good info. And i used it as my starting point. There was one problem with this thread. The XML used seems to be an old form of rewriting in Magento.
I found a (lost it) post by one of the Magento devs that shows a new and more clean way of defining this in XML.

In the last post i already created the [Namespace]_All.xml module config. And we can use it for this as well. So we start by telling Magento we are using our own [Namespace_]_Adminhtml module.

<[namespace]_Adminhtml>
    true
    local
    
        
    

create local/Namespace/Adminhtml/controllers/CustomerController.php

The next thing to do is create the actual controller. And add an include line on top to the original file. Magento does not use autoloading for the controllers in this way.

include_once("Mage/Adminhtml/controllers/CustomerController.php");

class [namespace]_Adminhtml_CustomerController extends Mage_Adminhtml_CustomerController
{
	public function somenewAction()
	{

	}
}

Now the Core CustomerController is replaced by our own namespaced version. But it still retains all functionality of the parent.

The only thing left is to create the config file for this module. And tell it to rewrite to the new [namespace]

Create local/[namespace]/Adminhtml/etc/config.xml


	
        <[namespace]_Adminhtml>
            0.1.0
        <[namespace]_Adminhtml>
    

	
    	
    		
    			
    				
    					<[namespace]_Adminhtml before="Mage_Adminhtml">[namespace]_Adminhtml
    				
    			
    		
    	
    

The config section is placed inside the admin tags. because the controller in question is an admin controller. We basically tell Magento that we will be using our own Adminhtml module instead of the Core one. But it will of course fall back on the Core functionality when methods have not been overwritten.

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Rewriting blocks in Magento

The last few days i have been toying with Magento. and mainly trying to wrap my head around the file structure. It takes quite some time to find all files. So i will be making notes here to keep track of my own progress :)

Today i wanted to add a tab in the customer section of the admin. I am working on a new module and this should be configurable on a per user basis. There for i needed an extra tab to the customer > Manage customers > [customer x] page.

The first challenge was to figure out where Magento stores the tab menu data. I was hoping this came from a database. But after some searching i couldn’t find any reference. It seems to be hard coded in tab files. The customer tab in question can be found here:

app/code/core/Mage/Adminhtml/Block/Customer/Edit/tabs.php

We could of course edit this class. But that’s not according the Magento way. We need to create a local copy of this class. preferably under my own namespace.

To make this happen we first need to tell Magento we are rewriting core modules. So we start of by creating the following file

app/etc/modules/[namespace]_All.xml

And we add the following lines



    
        
            true
            local
            
                
            
        
    

This will tell Magento we have a Core folder under our own namespace. But it still depends on the Mage_Core classes if they are not available in the namespaced location.

Next we need to setup the [namespace]_Core module. We create the folder structure under our own namspace

app/code/local/[namespace]/Core/etc

And we create a new config file here (config.xml) where we will do the actual class rewriting.



    
        <[namespace]_Core>
            0.1.0
        
    
    
        
        	
        		
        			[namespace]_Adminhtml_Block_Customer_Edit_Tabs
        		
        	
        
    

We use the tag to tell Magento we are rewriting a Block class. And then we setup the actual rewrite.

Mage_Adminhtml_Block_Customer_Edit_Tabs is now rewritten too [namespace]_Adminhtml_Block_Customer_Edit_Tabs

The only thing left now is to create the Block class which is located in

app/code/local/[namespace]/Adminhtml/Block/Customer/Edit/Tabs.php

class [namespace]_Adminhtml_Block_Customer_Edit_Tabs extends Mage_Adminhtml_Block_Customer_Edit_Tabs
{
    protected function _beforeToHtml()
    {
	$this->addTab('modulename', array(
            'label'     => Mage::helper('customer')->__('Modulename'),
            'class'     => 'ajax',
            'url'       => $this->getUrl('*/*/modulename', array('_current' => true)),
        ));

        $this->_updateActiveTab();
        return parent::_beforeToHtml();
    }
}
del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Nerdiness

Ok so i had nothing todo for a few minutes and found a link to this page. I am never really into this stuff. But it looked funny and i had nothing to do. So i walked through the questions… and the result :)

Supreme Nerd. Apply for a professorship at MIT now!!!.


I am nerdier than 91% of all people. Are you a nerd? Click here to take the Nerd Test, get nerdy images and jokes, and write on the nerd forum!

Another nerdy thing i picked up was that Ilia Alshanetsky’s scalar type hints patch has been merged with the PHP trunk. Great stuff. Have been waiting for this for a while.

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

A new look for lenss.nl

This long Easter weekend gave me some time to create a new theme for this blog. So after a day of work this is the result. I was a bit tired of the dark unreadable format. At the moment i am still tweaking here and there but it looks fine!

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Month of PHP Security 2010

After a successful experiment a while back Month of the PHP Bugs. Stefan Esser and SektionEins is at it again. This time with Month of PHP Security. A gathering for PHP and security gurus a like. The call for papers is open for submission.

There are some nice prices to walk away with. So what you waiting for?

  • New vulnerability in PHP [1] (not simple safe_mode, open_basedir bypass vulnerabilities)
  • New vulnerability in PHP related software [1] (popular 3rd party PHP extensions/patches)
  • Explain a single topic of PHP application security in detail (such as guidelines on how to store passwords)
  • Explain a complicated vulnerability in/attack against a PHP widespread application [1]
  • Explain a complicated topic of attacking PHP (e.g. explain how to exploit heap overflows in PHP’s heap implementation)
  • Explain how to attack encrypted PHP applications
  • Release of a new open source PHP security tool
  • Other topics related to PHP or PHP application security
del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati

Zend Framework Bootstrapping Modules

I am working on a small API for bluesignal and i wanted a modular architecture. I have done this before using the Zend Framework. But this time i wanted a bit more control while loading the modules. And adding a Bootstrap class would seem like a good option. The only example i could find involved loading all bootstraps on every request. Which doesn’t seem like a good idea. So after reading through the Manual and some blog posts. I decided to give it s shot my self.

The structure i want looks like this.

The application.ini file has the following contents:

includePaths.library = APPLICATION_PATH “/../library”
bootstrap.path = APPLICATION_PATH “/Bootstrap.php”
bootstrap.class = “Bootstrap”
resources.frontController.moduleDirectory = APPLICATION_PATH “/modules”
resources.modules[] = “default”
resources.modules[] = “admin”

includePaths
This sets the applications local library location. Any shared code for this application goes here.

bootstrap.path & class
Define the location and type of the Bootstrap class.

resources
Define the modules location and create a list of modules.

The main Bootstrap class

application/Bootstrap.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

Load the config parameters for this application and set some debugging settings if needed.

    protected function _initConfiguration()
    {
    	$app = $this->getApplication();
    	$config = $app->getOptions();

    	if (APPLICATION_ENV == 'development') {
	    	    error_reporting(E_ALL & E_STRICT);
	    	    if (isset($config['phpsettings'])) {
		    	        foreach ($config['phpsettings'] as $setting => $value) {
		    		        ini_set($setting, $value);
		    	        }
	    	    }
    	}
    }

We need autoloading here because we are using a class from the application library. Right now this causes a problem. A notice is thrown

Warning: include_once(FrontController.php) [function.include-once]: failed to open stream: No such file or directory in Zend/Loader.php on line 147

The application responds fine. And this problem seems to be a recurring issue (ZF-7224, ZF-7550) for the framework. Until now i have not find a graceful fix for this. besides a small patch reversion.

    protected function _initAutoload()
    {
		    $autoloader = Zend_Loader_Autoloader::getInstance();
		    $autoloader->setFallbackAutoloader(true);

		    return $autoloader;
    }

Setup the controller to register the Bluess_Modules_Loader plug-in. And set the prefixDefaultModule parameter so we can prefix the default module controllers as well. Just for the sake of consistency. The Bluess_ namespace is part of my API. And can be changed at will.

   protected function _initController()
    {
    	$this->bootstrap('FrontController');
    	$controller = $this->getResource('FrontController');
       $modules = $controller->getControllerDirectory();
       $controller->setParam('prefixDefaultModule', true);

        $controller->registerPlugin(
               new Bluess_Modules_Loader($modules)
        );

        return $controller;
    }

Now the last method. which is a bit weird. And i am probably missing a key factor here. But if this method resource is not declared only the default module functions. When declared empty all modules function as they should. This would indicate that this method could be used to load the modules. But i haven’t found a way to achieve this yet. Except for loading all modules in a row. Which makes no sense for this purpose. So we leave it empty.

protected function _initModules()
    {
		// Call to prevent ZF from loading all modules
    }

The most important part here is the controller plug-in. This will be the place where module bootstraps are called from.

application/../library/Bluess/Modules/Loader.php

class Bluess_Modules_Loader extends Zend_Controller_Plugin_Abstract
{
	protected $_modules;

Setup the plug-in by passing the applications module list.

	public function __construct(array $modulesList)
	{
		$this->_modules = $modulesList;
	}

The dispatchLoopStartup method will be called on every request and will do the magic. Based on the current module name we create a new Zend_Application with the current modules config file module.ini. And we bootstrap it.

	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
	{
		$module = $request->getModuleName();

		if (!isset($this->_modules[$module])) {
			throw new Exception("Module does not exist!");
		}

		$bootstrapPath = $this->_modules[$module];

		$bootstrapFile = dirname($bootstrapPath) . '/Bootstrap.php';
        $class         = ucfirst($module) . '_Bootstrap';
        $application   = new Zend_Application(
        	APPLICATION_ENV,
    		APPLICATION_PATH . '/modules/' . $module . '/configs/module.ini'
		);  

        if (Zend_Loader::loadFile('Bootstrap.php', dirname($bootstrapPath))
        	&& class_exists($class)) {
            $bootstrap = new $class($application);
            $bootstrap->bootstrap();
        }
	}
}

Now setup the default module. Once this is done it’s a nice example for further modules. Make sure the module has it’s own layout set.

application/modules/default/configs/module.ini

default.resources.layout.layout = “default”
default.resources.layout.layoutPath = APPLICATION_PATH “/modules/default/layout”

Setup the modules bootstrap and use it to set the modules model location.

application/modules/default/Bootstrap.php

class Default_Bootstrap extends Zend_Application_Module_Bootstrap
{
	protected $_moduleName = 'default';

	protected function _initConfiguration()
    {
		$options = $this->getApplication()->getOptions();

    	set_include_path(implode(PATH_SEPARATOR, array(
		    realpath(APPLICATION_PATH . '/modules/' . $this->_moduleName . '/models'),
		    get_include_path(),
		)));

		return $options;
    }
}

That’s all. Now make sure your layout is set correctly and the controllers are prefixed

application/modules/default/layout/default.phtml

echo $this->layout()->content;

application/modules/default/controllers/IndexController.php

class Default_IndexController extends Zend_Controller_Action
{

It took me a while to get this working like i had it in my mind. But it’s going the right way. If your interested in a working copy. You can download one here.

UPDATE

Matthew has a nice post about some do’s and don’ts concerning module based applications

del.icio.us Digg DZone reddit SlashDot StumbleUpon Technorati