<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Magento Design and Development &#187; class</title>
	<atom:link href="http://inchoo.net/tag/class/feed/" rel="self" type="application/rss+xml" />
	<link>http://inchoo.net</link>
	<description>Magento Design and Magento Development Professionals - Inchoo</description>
	<lastBuildDate>Thu, 02 Feb 2012 13:42:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Custom Pagination in Symfony 2</title>
		<link>http://inchoo.net/tools-frameworks/symfony-2-pagination/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony-2-pagination/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 11:43:43 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9129</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 PR12. Might not work on later releases! There is a newer version article about Symfony2 pagination that is compatible with Symfony2 &#8211; beta1. Using Symfony 2, I noticed that there is no pagination included in framework &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony-2-pagination/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;"><strong>NOTE: Tested on Symfony2 PR12. Might not work on later releases!<br />
</strong><a href="http://inchoo.net/tools-frameworks/paginator-symfony2-beta/"><em>There is a newer version article about Symfony2 pagination that is compatible with Symfony2 &#8211; beta1.</em></a><strong></strong></p>
<p style="text-align: justify;">Using Symfony 2, I noticed that there is no pagination  included in framework (just some additional Bundle for download -and  it uses Zend pagination but I don&#8217;t want to mix Zend into my Symfony 2 project), so I decided to write class for that on my own.<span id="more-9129"></span>This class is just in <em>basic</em> format (in the future will be added more features) but for basic purposes is usable.</p>
<p style="text-align: justify;"><em>Here is the case:</em> I have view with list of items loaded from database and need pagination for that.</p>
<p style="text-align: justify;"><em>Basic idea:</em><br />
Create <em>&#8216;Paginator&#8217;</em> class and put all logic of pagination inside that class, and leave all database logic to Entity classes.</p>
<p style="text-align: justify;">Here is the source code:</p>
<p style="text-align: justify;">
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * Class to generate pagination for items
 *
 * @author Darko Goleš
 * @www.inchoo.net
 */
namespace Surgeworks\AdminBundle\Helpers;

class Paginator {

 //current displayed page
 protected $currentpage;
 //limit items on one page
 protected $limit;
 //total number of pages that will be generated
 protected $numpages;
 //total items loaded from database
 protected $itemscount;
 //starting item number to be shown on page
 protected $offset;

 function __construct($itemscount) {
 //set total items count from controller
 $this-&gt;itemscount = $itemscount;
 //get params from request URL
 $this-&gt;getParamsFromRequest();
 //Calculate number of pages total
 $this-&gt;getNumPages();
 //Calculate first shown item on current page
 $this-&gt;calculateOffset();
 }

 private function getParamsFromRequest() {
 //If current page number is set in URL
 if (isset($_GET['page'])) {
 $this-&gt;currentpage = $_GET['page'];
 } else {
 //else set default page to render
 $this-&gt;currentpage = 1;
 }
 //If limit is defined in URL
 if (isset($_GET['limit'])) {
 $this-&gt;limit = $_GET['limit'];
 } else {   //else set default limit to 20
 $this-&gt;limit = 10;
 }
 //If currentpage is set to null or is set to 0 or less
 //set it to default (1)
 if (($this-&gt;currentpage == null) || ($this-&gt;currentpage &lt; 1)) {
 $this-&gt;currentpage = 1;
 }
 //if limit is set to null set it to default (10)
 if (($this-&gt;limit == null)) {
 $this-&gt;limit = 10;
 //if limit is any number less than 1 then set it to 0 for displaying
 //items without limit
 } else if ($this-&gt;limit &lt; 1) {
 $this-&gt;limit = 0;
 }
 }

 private function getNumPages() {
 //If limit is set to 0 or set to number bigger then total items count
 //display all in one page
 if (($this-&gt;limit &lt; 1) || ($this-&gt;limit &gt; $this-&gt;itemscount)) {
 $this-&gt;numpages = 1;
 } else {
 //Calculate rest numbers from dividing operation so we can add one
 //more page for this items
 $restItemsNum = $this-&gt;itemscount % $this-&gt;limit;
 //if rest items &gt; 0 then add one more page else just divide items
 //by limit
 $restItemsNum &gt; 0 ? $this-&gt;numpages = intval($this-&gt;itemscount / $this-&gt;limit) + 1 : $this-&gt;numpages = intval($this-&gt;itemscount / $this-&gt;limit);
 }
 }

 private function calculateOffset() {
 //Calculet offset for items based on current page number
 $this-&gt;offset = ($this-&gt;currentpage - 1) * $this-&gt;limit;
 }

 //Returns HTML string with paginator elements - will be used from Controller
 public function RenderPaginator() {
 $html = '';
 //Insert all in one div tag
 $html.= '&lt;div&gt;';
 //We need this form for sumbitting limit into URL via GET call
 $html.='&lt;form id= &quot;paginator&quot; name=&quot;paginator&quot; method=&quot;get&quot; action=&quot;#&quot; &gt;';
 //When limit is changed - just submit form
 $html.= '&lt;select name=&quot;limit&quot; onchange=&quot;javascript:document.forms.paginator.submit()&quot;&gt;';
 $html.= '&lt;option value=&quot;10&quot; ';
 if ($this-&gt;limit == 10) {
 $html.='selected';
 } $html.='&gt;10&lt;/option&gt;';
 $html.= '&lt;option value=&quot;20&quot; ';
 if ($this-&gt;limit == 20) {
 $html.='selected';
 } $html.='&gt;20&lt;/option&gt;';
 $html.= '&lt;option value=&quot;30&quot; ';
 if ($this-&gt;limit == 30) {
 $html.='selected';
 } $html.='&gt;30&lt;/option&gt;';
 $html.= '&lt;option value=&quot;50&quot; ';
 if ($this-&gt;limit == 50) {
 $html.='selected';
 } $html.='&gt;50&lt;/option&gt;';
 $html.= '&lt;option value=&quot;100&quot; ';
 if ($this-&gt;limit == 100) {
 $html.='selected';
 } $html.='&gt;100&lt;/option&gt;';
 $html.= '&lt;option value=&quot;500&quot; ';
 if ($this-&gt;limit == 500) {
 $html.='selected';
 } $html.='&gt;500&lt;/option&gt;';
 $html.= '&lt;option value=&quot;0&quot; ';
 if ($this-&gt;limit == 0) {
 $html.='selected';
 } $html.='&gt;All&lt;/option&gt;';
 $html.='&lt;/select&gt;';
 $html.='&lt;/form&gt;';
 $html.='&lt;ul&gt;';

 //Generate links for pages
 for ($i = 1; $i &lt; $this-&gt;numpages + 1; $i++) {

 $html.='&lt;li&gt;&lt;a href=&quot;' . $_SERVER['PHP_SELF'] . '?limit=' . $this-&gt;limit . '&amp;amp;page=' . $i . '&quot;&gt;' . $i . '&lt;/a&gt;&lt;/li&gt;';
 }
 $html.='&lt;/ul&gt;';
 $html.= '&lt;/div&gt;';

 return $html;
 }

 //For using from controller
 public function getLimit() {
 return $this-&gt;limit;
 }
 //For using from controller
 public function getOffset() {
 return $this-&gt;offset;
 }

}
</pre>
<p style="text-align: justify;">Now let&#8217;s look in database repository class:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
namespace Surgeworks\AdminBundle\Entity;

use Doctrine\ORM\EntityRepository;

class LanguageRepository extends EntityRepository {

 public function getLanguagesListWithPagination($order_by = array(), $offset = 0, $limit = 0) {
 //Create query builder for languages table
 $qb = $this-&gt;createQueryBuilder('l');

 //Show all if offset and limit not set, also show all when limit is 0
 if ((isset($offset)) &amp;&amp; (isset($limit))) {
 if ($limit &gt; 0) {
 $qb-&gt;setFirstResult($offset);
 $qb-&gt;setMaxResults($limit);
 }
 //else we want to display all items on one page
 }
 //Adding defined sorting parameters from variable into query
 foreach ($order_by as $key =&gt; $value) {
 $qb-&gt;add('orderBy', 'l.' . $key . ' ' . $value);
 }
 //Get our query
 $q = $qb-&gt;getQuery();
 //Return result
 return $q-&gt;getResult();
 }

 public function getLanguagesCount() {
 //Create query builder for languages table
 $qb = $this-&gt;createQueryBuilder('l');
 //Add Count expression to query
 $qb-&gt;add('select', $qb-&gt;expr()-&gt;count('l'));
 //Get our query
 $q = $qb-&gt;getQuery();
 //Return number of items
 return $q-&gt;getSingleScalarResult();
 }

}
</pre>
<p style="text-align: justify;">Now it&#8217;s time to use it in our controller action:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Surgeworks\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;
use Surgeworks\AdminBundle\Forms\LanguageForm;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Surgeworks\AdminBundle\Helpers\Paginator;

class LanguagesController extends Controller {

 /**
 * @extra:Route(&quot;/admin/languages&quot;, name=&quot;_admin_languages&quot;)
 * @extra:Template()
 */
 public function indexAction() {

 //order of items from database
 $order_by = array();
 //get Entity manager instance
 $em = $this-&gt;get('doctrine.orm.entity_manager');
 //get repository for class 'Language' : LanguageRepository.php
 $repository = $em-&gt;getRepository('Surgeworks\AdminBundle\Entity\Language');
 //get count of languages for using with Paginator class
 //Using custom made database query function in LanguageRepository class
 $languagesCount = $repository-&gt;getLanguagesCount();
 //When creating new paginator object it takes care for pages and items
 //organization based on numbers of items from database and limit variable in $_GET
 $paginator = new Paginator($languagesCount);
 //get returned HTML string from Paginator to render paginator HTML
 //elements in the template
 $strPaginator = $paginator-&gt;RenderPaginator();

 //If we have POST variable defined, than it is defined order of items
 //from inside form (clicking on sorting column for example)
 if ('POST' === $this-&gt;get('request')-&gt;getMethod()) {
 $order_by = array($_POST['filter_order'] =&gt; $_POST['filter_order_Dir']);
 $sort_direction = $_POST['filter_order_Dir'] == 'asc' ? 'desc' : 'asc';
 } else {
 //We know that nothing is changed for ordering columns -
 //this is alse default order of items when page is first opened
 $order_by = array('sort_order' =&gt; 'asc', 'id' =&gt; 'asc');
 $sort_direction = 'desc';
 }
 //To fill $languages for forwarding it to the template, we first call database function
 //with $offset and $limit to get items we wanted
 $languages = $repository-&gt;getLanguagesListWithPagination($order_by, $paginator-&gt;getOffset(), $paginator-&gt;getLimit());
 //Finally - return array to templating engine for displaying data.
 return array('languages' =&gt; $languages, 'sort_dir' =&gt; $sort_direction, 'paginator' =&gt; $strPaginator);
 }
...
</pre>
<p style="text-align: justify;">Then in your twig template show it like that:</p>
<pre class="brush: php; title: ; notranslate">
{{ paginator|raw }}
</pre>
<p style="text-align: justify;">and maybe after all of this, add some CSS styles to make that paginator beautiful&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony-2-pagination/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Making use of Magento getSingleton method</title>
		<link>http://inchoo.net/ecommerce/magento/making-use-of-magento-getsingleton-method/</link>
		<comments>http://inchoo.net/ecommerce/magento/making-use-of-magento-getsingleton-method/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 21:26:04 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[object]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=170</guid>
		<description><![CDATA[In one of my previous articles I showed you how to use getModel and getData methods in Magento. Although we should not put those to methods at the same level, since I&#8217;d say the getModel is a bit more higher. &#8230;<p><a href="http://inchoo.net/ecommerce/magento/making-use-of-magento-getsingleton-method/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>In one of my previous <a href="http://ajzele.net/2008/10/05/getting-things-in-magento-by-getmodel-and-getdata-methods/">articles</a> I showed you how to use getModel and getData methods in Magento. Although we should not put those to methods at the same level, since I&#8217;d say the getModel is a bit more higher. Higher in sense, you first use the geModel to create the instance of object then you use getData to retrieve the data from that instance. I have said it before, and I&#8217;m saying it again; Magento is a great peace of full OOP power of PHP. It&#8217;s architecture is something not yet widely seen in CMS solutions.</p>
<p>One of the architectural goodies of Magento is it&#8217;s Singleton design pattern. In short, Singleton design pattern ensures a class has only one instance. Therefore one should provide a global point of access to that single instance of a class.<span id="more-170"></span></p>
<p>So why would you want to limit yourself to only one instance? Let&#8217;s say you have an application that utilizes database connection. Why would you create multiple instance of the same database connection object? What if you had references to an object in multiple places in your application? Wouldn&#8217;t you like to avoid the overhead of creating a new instance of that object for each reference? Then there is the case where you might want to pass the object&#8217;s state from one reference to another rather than always starting from an initial state.</p>
<p>Inside the Mage.php file of Magento system there is a <strong>getSingleton</strong> method (function if you prefer). Since it&#8217;s footprint is rather small, I&#8217;ll copy paste the code for you to see it.</p>
<p><strong>public static function getSingleton</strong>($modelClass=&#8221;, array $arguments=array())<br />
{<br />
$registryKey = &#8216;_singleton/&#8217;.$modelClass;<br />
if (!Mage::registry($registryKey)) {<br />
Mage::register($registryKey, Mage::getModel($modelClass, $arguments));<br />
}<br />
return Mage::registry($registryKey);<br />
}</p>
<p>First, notice the word static. In PHP and in other OOP languages keyword static stands for something like &#8220;this can be called on non objects, directly from class&#8221;. Now let me show you the footprint of the getModel method.</p>
<p><strong>public static function getModel</strong>($modelClass=&#8221;, $arguments=array())<br />
{<br />
return Mage::getConfig()-&gt;getModelInstance($modelClass, $arguments);<br />
}</p>
<p>Do you notice the <strong>parameters inside the brackets</strong>? They are the same for both of theme. Where am I getting with this? Well, I already showed you how to figure out the list of all of the available parameters in one of my previous <a href="http://ajzele.net/getting-things-in-magento-by-getmodel-and-getdata-methods/">articles</a> on my <a href="http://ajzele.net">site</a>. So all we need to do at this point is, play with those parameters using <strong>getSingleton()</strong> method and observe the results.</p>
<p>Most important thing you need to remember is that using <strong>getSingleton</strong> you are calling already instantiated object. So if you get the empty array as a result, it means the object is empty. Only the blueprint is there, but nothing is loaded in it. We had the similar case using <strong>getModel(&#8216;<em>catalog/product</em>&#8216;)</strong> on some pages. If we done <strong>var_dump</strong> or <strong>print_r</strong> we could saw the return <strong>array</strong> was <strong>empty</strong>. Then we had to use the load method to load some data into our newly instantiated object.</p>
<p>What I&#8217;m trying to say, you need to play with it to get the feeling. Some models will return data rich objects some will return empty arrays. If we were to do <strong>Mage::getSingleton(&#8216;catalog/session)</strong> on <strong>view.phtml</strong> file we would retrieve an array with some useful data in it. Do not get confused with me mentioning the view.phmtl file, it&#8217;s just he file i like to use to test the code. Using <strong>Mage::getSingleton(&#8216;core/session)</strong> would retrieve us some more data. You get the picture. <strong>Test, test, test&#8230;</strong> What&#8217;s great about the whole thing is that naming in Magento is perfectly logical so most of the time you will probably find stuff you need in few minutes or so.</p>
<p>For the end here are some screenshots for you to see the results of calling getSingleton with <strong>catalog/product</strong> and <strong>catalog/session</strong> parametars.</p>
<p><a href="http://inchoo.net/wp-content/uploads/2008/10/getsingletoncatalogproduct.png"><img class="alignnone size-thumbnail wp-image-172" title="getsingletoncatalogproduct" src="http://inchoo.net/wp-content/uploads/2008/10/getsingletoncatalogproduct-150x85.png" alt="" width="150" height="85" /></a> <a href="http://inchoo.net/wp-content/uploads/2008/10/getsingletoncatalogsession.png"><img class="alignnone size-thumbnail wp-image-174" title="getsingletoncatalogsession" src="http://inchoo.net/wp-content/uploads/2008/10/getsingletoncatalogsession-150x85.png" alt="" width="150" height="85" /></a></p>
<p>Hope this will be useful for some of you.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/making-use-of-magento-getsingleton-method/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Figuring out Magento object context</title>
		<link>http://inchoo.net/tools-frameworks/finding-out-magento-object-context/</link>
		<comments>http://inchoo.net/tools-frameworks/finding-out-magento-object-context/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 20:01:30 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[view]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=94</guid>
		<description><![CDATA[One of the problems working under the hood of the Magento CMS is determining the context of $this. If you are about to do any advanced stuff with your template, besides layout changes, you need to get familiar with Magento&#8217;s &#8230;<p><a href="http://inchoo.net/tools-frameworks/finding-out-magento-object-context/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>One of the problems working under the hood of the Magento CMS is determining the context of <strong>$this</strong>. If you are about to do any advanced stuff with your template, besides layout changes, you need to get familiar with Magento&#8217;s objects (classes).</p>
<p>Let&#8217;s have a look at the <strong>/app/design/frontend/default/default/template/catalog/product/view.phtml</strong> file. If you open this file and execute <strong>var_dump($this)</strong> your browser will return empty page after a short period of delay. By page I mean on the product view page; the one you see when you click on Magetno product. Experienced users will open <strong>PHP error log</strong> and notice the error message caused by <strong>var_dump()</strong>. <span id="more-94"></span><strong>Error message</strong>:<br />
<em>PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 121374721 bytes)</em></p>
<p>I like using <strong>print_r()</strong> and <strong>var_dump()</strong>, mostly because so far I had no positive experience using fancy debug or any other debugger with systems like Magento.</p>
<p><em><strong>Why is PHP throwing errors then</strong></em>? If you google out the error PHP has thrown at you, you&#8217;ll see that PHP 5.2 has memory limit. Follow the link <a title="PHP Memory Limit" href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit" target="_blank">http://www.php.net/manual/en/ini.core.php#ini.memory-limit</a> to see how and what exactly.</p>
<p>Google search gave me some useful results trying to solve my problems. I found <strong>Krumo</strong> at <a title="Krumo" href="http://krumo.sourceforge.net/" target="_blank">http://krumo.sourceforge.net/</a>. It&#8217;s a PHP debugging tool, replacement for print_r() and var_dump(). After setting up Krumo and running it on Magento it gave me exactly what I wanted. It gave me the object type of the dumped file; in this case it gave me object type of $this.</p>
<p>If you&#8217;re using an IDE studio with code completion support like <strong>NuSphere PhpED</strong>, <strong>ZendStudio</strong> or <strong>NetBeans</strong> and you decide to do something like $this-&gt; you won&#8217;t get any methods listed. I haven&#8217;t yet seen the IDE that can perform this kind of smart logic and figure out the context of $this by it self.</p>
<p>What you can do is use the information obtained by krumo::dump($this). Performing <strong>krumo::dump($this)</strong> on <strong>/app/design/frontend/default/default/template/catalog/product/view.phtml</strong> file will return object type, <strong>Mage_Catalog_Block_Product_View</strong>.</p>
<p>Now if you do</p>
<p><em>Mage_Catalog_Block_Product_View::</em></p>
<p>your IDE supporting code completion will give you a drop down of all the available methods, let&#8217;s say canEmailToFriend();</p>
<p><em>Mage_Catalog_Block_Product_View::canEmailToFriend();</em></p>
<p>Now all you need to do is to replace  <strong><em>Mage_Catalog_Block_Product_View</em></strong> with <em><strong>$this</strong></em> like</p>
<p><em>$this-&gt;canEmailToFriend();</em></p>
<p>And you&#8217;re done. All of this may look like &#8220;why do I need this&#8221;. What you need it a smart IDE, one that can figure out the context of $this by it self and call the methods accordingly. No IDE currently does that, if I&#8217;m not missing on something. For now I see no better solution to retrieve the object context of $this across all those Magento files.</p>
<p>If you need some help setting up Krumo with Magento you can read my other, somewhat detailed <a title="ActiveCodeline debugging magento using krumo" href="http://ajzele.net/debugging-magento-using-krumo/" target="_blank">article</a> on <a title="ActiveCodeline" href="http://ajzele.net" target="_blank">activecodeline.com</a>.</p>
<p>Hope this was useful for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/finding-out-magento-object-context/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

