Magento – Why use createBlock() and setTemplate() methods over creating a block via .xml file in /layout subdir

best practiceblockslayouttemplate

I've seen examples in extensions and in core where blocks are created through PHP code, e.g. in a controller action:

$block = $this->getLayout()->createBlock("company_module/...");

Or a block sets its own template, usually in the _construct()

$this->setTemplate("... .phtml");

I can see the programmatic approach being necessary if there is business logic involved that decides which block to create (or perhaps not create) and which .phtml template to set, depending on the circumstances.

But there are plenty of examples where there appears to be no business logic involved, yet the developer decided NOT to use the declarative approach of the .xml

Why would one want to NOT use .xml for creating blocks? What is best practice?

Best Answer

It depends on several things. This is because each and every developer has different approaches to different scenarios.

For an example, suppose I need to do change a template of a core block. I can do it programmatically or via layout update. Now some developers think in this way

"What I want to do is to just change a template. Then why should I define a new layout update file in config.xml, put the layout file in the theme folder and then construct xml to change the template of that block?? Let us approach this programmatically"

Now some people think this way

"I want to change the template of this block. It is clearly a layout update. So it should be done via layout update. Let us go with a new layout update file and do this in a fraction of second"

So this is purely depends upon a programmer. Someone like to do certain things in programmatic way. Some others love layout update technique. Both are correct and we can't blame anyone.

But suppose, if our module requires a lot of layout updates, then doing all those things programmatically will not be a good approach. In that case, we should consider to use a layout update xml file. That is more elegant and cleaner method. But for small layout udpates or if we want to apply some "dynamic logics" to layout, then it is convenient to go on with programmatic approach.

Related Topic