Basic PHP stuff every frontend Magento developer should know

Unlike backend development, term frontend development usually refers to a little less programming knowledge requirement. In regards to that, here are few truly essential snippets every Magento frontend developer should know and understand.

I found a pretty nice book that could really be of use for frontend developers. Its called PHP for Absolute Beginners by Jason Lengstorf. I would strongly recommend Chapter 2, Understanding PHP: Language basics.

And here are some practical examples.

Snippet 1: Check if variable is object and of which class

<pre>< ?php Zend_Debug::dump(get_class($this), 'get_class') ?></pre>
< ?php 
 * Once you do get_class you will get a class name.
 * With class name you can do something like
 * $this = new Mage_Page_Block_Html_Header();
 * then IDE will give you autocomplete on things like "$this->"
 * Just remember to comment the out the 
 * //$this = new Mage_Page_Block_Html_Header();
 * once you are done

Snippet 2: Do a basic dump of variable to see its “content”/value

<pre>< ?php Zend_Debug::dump($this->debug(), 'debug') ?></pre>

Snippet 3: Read the value of object properties/attributes
(Note that $_product var is just example, it can be any Magento/Varien object)

<pre>< ?php Zend_Debug::dump($_product->getData('attribute_name')) ?></pre>

Snippet 4: Read the value of object properties/attributes
(Does the same thing as Snippet 3)

<pre>< ?php Zend_Debug::dump($_product->getAttributeName()) ?></pre>

Snippet 5: Compare the value of attribute/property to some other value

< ?php if($_product->getSku() == 'sku-xxx-ppp-222'): ?>
	Ouput something only if product Sku is equal to 'sku-xxx-ppp-222'. 
< ?php endif; ?>

Snippet 6: Loop trough Magento collection object
(Check if something is a collection, if we can iterate trough it)

< ?php if($someVar instanceof Varien_Data_Collection): ?>
	< ?php foreach($someVar as $k => $v): ?>
		<li>Some value: < ?php echo $v ?></li>
	< ?php endforeach; ?>
< ?php endif; ?>


  1. Follow up to Peeter’s get_include_files, this works OK at the end of index.php

    echo '<pre>';
    echo '</pre>';
  2. As useful as get_class_methods is, with Magento I normally find it a bit of a waste of time, as it always gives you sooooo many methods. I guess that’s the problem with a large php project where you have classes extended multiple times.

  3. You might as well add

    * to the list, they always have hard time to follow what templates are used in some page so they just could add this method at the end of index.php

    * greps your methods that you’re looking for: grep ‘getConfig’ app/code -rs

    * get_class_methods is also quite helpful to get the full list of methods available if you’re not found of code insight

Leave a Reply

