<?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; development</title>
	<atom:link href="http://inchoo.net/tag/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://inchoo.net</link>
	<description>Magento Design and Magento Development Professionals - Inchoo</description>
	<lastBuildDate>Mon, 06 Feb 2012 08:30:33 +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>Configuring Magento for development</title>
		<link>http://inchoo.net/ecommerce/magento/configuring-magento-for-development/</link>
		<comments>http://inchoo.net/ecommerce/magento/configuring-magento-for-development/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 06:41:22 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Starting up]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[development]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=11033</guid>
		<description><![CDATA[New to the Magento or just used to doing things one way? Here are few tips for configuring Magento for development, in case you overlooked them. Please note, the more proper title of this article would be something like: Configuring &#8230;<p><a href="http://inchoo.net/ecommerce/magento/configuring-magento-for-development/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>New to the Magento or just used to doing things one way? Here are few tips for configuring Magento for development, in case you overlooked them. Please note, the more proper title of this article would be something like: Configuring Magento for development on local machine (after installation config). Meaning the tips outlined here only apply after the Magento is already installed.<span id="more-11033"></span></p>
<p>Here are the steps that you should do in order to set your Magento more suited for development:</p>
<ul>
<li>System > Cache Management > Disable All</li>
<li>System > Configuration > Advanced > Developer > Log Settings > Enabled => Yes</li>
<li>System > Configuration > Web > Search Engine Optimization > Use Wbe Server Rewrites => Yes</li>
<li>System > Index Management > Reindex All</li>
<li>Open .htaccess and set: SetEnv MAGE_IS_DEVELOPER_MODE &#8220;true&#8221; at the end of the file</li>
<li>Open .htaccess and set: php_value display_errors On somewhere within &#60;IfModule mod_php5.c&#62;</li>
<li>Rename /errors/local.xml.sample to /errors/local.xml</li>
<li>Create one sample customer with full valid American address (for example use US/California, city Alamo with ZIP 94507), and one with full valid non American address (other country) to test payment and shipping gateways properly</li>
<li>Compensate for the possible lack of email server by doing something like explained in <a href="http://inchoo.net/ecommerce/magento/magento-l-e-s-s/">this article</a></li>
</ul>
<p>Hope it helps.</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/configuring-magento-for-development/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Creating simple Symfony2 service</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-service/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-service/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 07:10:09 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[services]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10698</guid>
		<description><![CDATA[I am not talking about web services, but I am talking about symfony2 service container and the way of basic creating services inside Symfony2 project that are accessible from all other bundles via service container. Why do I need to &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-service/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>I am not talking about web services, but I am talking about symfony2 service container and the way of basic creating services inside Symfony2 project that are accessible from all other bundles via service container.</p>
<p>Why do I need to make some part of code like service inside Symfony2 anyway?</p>
<p>There is one possible problem:<span id="more-10698"></span></p>
<p>When I started my project, I started with administrator area of application for handling CRUD operations. But this bundle is just for administrators of application. On the other side, I have to provide REST web service API that will be consumed by various devices (iPhone, Android, …).<br />
I don&#8217;t want to put together my code for administrators and web services API code. So, after AdminBundle was finished, I decided to make another bundle inside project that will be &#8216;public&#8217; side bundle and called it: ApiBundle. Inside this I will provide data that is entered and organized inside Admin area of application with REST based API .</p>
<p>For API, I also need same Entities used inside Admin Bundle that will handle database layer for web services too.</p>
<p>If I try to use  my entities that currently are inside AdminBundle from API bundle it doesn&#8217;t sounds logically to me. What if I want to separate API bundle from Admin Bundle in the future. How will I then use my entities in both? Duplicate them? I don&#8217;t think so!</p>
<p>For purposes like this, it&#8217;s better to create one more, separate Bundle that I called &#8216;CoreBundle&#8217; that will hold all shared classes and also my entity classes for both: AdminBundle and ApiBundle.</p>
<p>Accessing those classes from AdminBundle and also ApiBundle I want to be via service container, so all of these methods are separated and public available for using in other bundles.</p>
<p>Because of that, I want to build simple Symfony2 services: one for AdminBundle and second for ApiBundle – to separate application logic.</p>
<p>Inside CoreBundle, I made folder called &#8216;Services&#8217; and inside I put two files: Admin.php and Api.php.</p>
<p>Inside CoreBundle\Resources\config I made some changes to the file called &#8216;services.xml&#8217;:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; ?&gt;

&lt;container xmlns=&quot;http://symfony.com/schema/dic/services&quot;
  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
  xsi:schemaLocation=&quot;http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd&quot;&gt;

  &lt;parameters&gt;
     &lt;parameter key=&quot;surgeworks_core.admin.class&quot;&gt;Surgeworks\CoreBundle\Services\Admin&lt;/parameter&gt;
     &lt;parameter key=&quot;surgeworks_core.api.class&quot;&gt;Surgeworks\CoreBundle\Services\Api&lt;/parameter&gt;
  &lt;/parameters&gt;

  &lt;services&gt;
     &lt;service id=&quot;surgeworks_core.admin&quot;&gt;
        &lt;argument type=&quot;service&quot; id=&quot;service_container&quot; /&gt;
     &lt;/service&gt;
     &lt;service id=&quot;surgeworks_core.api&quot;&gt;
        &lt;argument type=&quot;service&quot; id=&quot;service_container&quot; /&gt;
     &lt;/service&gt;
  &lt;/services&gt;
&lt;/container&gt;
</pre>
<pre class="brush: php; title: ; notranslate">

//...

&lt;?php
// Surgeworks\CoreBundle\DependencyInjection\Configuration.php
namespace Surgeworks\CoreBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
 {
   $treeBuilder = new TreeBuilder();
   $rootNode = $treeBuilder-&gt;root('surgeworks_core');

// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.

   return $treeBuilder;
 }
}

//...
</pre>
<p>I just have to write my own functions inside mentioned Admin.php and Api.php and call them via service container from amy bundle&#8217;s controller:</p>
<pre class="brush: php; title: ; notranslate">

//some controller
public function testAction()
{
   $statusesCount = $this-&gt;get('surgeworks_core.admin')-&gt; Statuses_getCount();
}
</pre>
<p>And function inside Admin.php:</p>
<pre class="brush: php; title: ; notranslate">

public function Statuses_getCount() {
   $repository = $this-&gt;getEm()-&gt;getRepository('Surgeworks\CoreBundle\Entity\Status');
   $statusesCount = $repository-&gt;getStatusesCount();
   return $statusesCount;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-service/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Creating your own web shop &#8211; Part 1: Where to start</title>
		<link>http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/</link>
		<comments>http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/#comments</comments>
		<pubDate>Sun, 07 Aug 2011 09:56:48 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[E-Commerce]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[web shop]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10576</guid>
		<description><![CDATA[Creating your own web shop can be a tedious task, both technically and time consuming. Not to mention there are tens of quality PHP based web shop systems out there available for free. One of the best if you ask &#8230;<p><a href="http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>Creating your own web shop can be a tedious task, both technically and time consuming. Not to mention there are tens of quality PHP based web shop systems out there available for free. One of the best if you ask me is Magento, which exceeds the term web shop system by even bigger term &#8220;platform&#8221;. However, regardless of how some much a given system/platform is feature rich there are always those special clients with special requests which exceed the possibilities of even the mightiest eCommerce systems/platforms out there.<span id="more-10576"></span></p>
<p>In my experience, usually these type of clients are either big enterprise level clients or &#8220;small first time running a web shop&#8221; client. Big enterprise level clients usually know very well what they want as they outgrown the features even the most feature rich platforms can give them out of the box.</p>
<p>Before I go any further, I would just like to clarify one thing. This article is by no means advice or suggestion you should consider building your own web shop solution over choosing Magento CE, PE, or EE or possibly some other professional/enterprise web shop platform. In my opinion doing so would only be justified in situations where desired feature list massively exceeds the features offered by any of Magento versions, or if your budget and delivery date are of no or little importance.</p>
<p>Seems like building your own web shop system these days comes down to (1) satisfying your personal needs as a developer (meaning you got some time on your hand and you wish to play with building something out of the scratch just so see if you can do it), (2) You really have a special feature list you need to implement in your own web shop while at the same time you do not need all or any of the features offered by powerful web shops that are already there. Everything else seems just like reinventing a wheel, because all it takes is to develop extensions/modules for existing systems/platforms and save yourself both money and time.</p>
<p>OK, enough for the introduction. Let&#8221;s get down to it. Where to start when creating your own shop? I would say there are five major topic that need to be outlined: </p>
<ul>
<li>Feature list (<i>in a broader term this should come with proper software requirements, as noted by <a href="http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/#comment-22233">beeplogic</a> below in comments</i>),</li>
<li>Development platform selection,</li>
<li>Overall budget</li>
<li>Available resources</li>
<li>Expected date of delivery</li>
</ul>
<p><strong>Feature list</strong> should cover a full list of requested features, like: Customer Single Sign On (Facebook, Twitter), One Step Checkout, Implementation of XYZ payment gateway, Product Review/Comments System, Multi-language, Multi-currency, Email Notifications System, Product types (standard, downloadable, bundle), etc.</p>
<p><strong>Development platform selection</strong> should evaluate possibly several different platforms that might be interested for our project. For example, usage of Zend Framework over Symfony over CodeIgniter over cakePHP etc., if we are talking about PHP platforms.</p>
<p><strong>Overall budget</strong> is pretty clear. Probably the most important thing here to note is that you should never plan your project on &#8220;how to spent entire budget&#8221; but more like &#8220;how to deliver all or most of the features by expected delivery date not exceeding the overall budget&#8221; concept. Sometimes clients need reality check, and they need to be forced to either prioritize or dismiss certain features if the budget is low.</p>
<p><strong>Available resources</strong> are all those people (developers, designers, project manager) in your team which you know will be working on a given project.</p>
<p><strong>Expected date of delivery</strong> is extremely important in the big picture as it represents the link between feature list, overall budget and available resources. For example, imagine someone gives you a budget of $500K, in order to deliver a system with 50 outlined features with a team of 7 experienced people working on it within 3 months. Let&#8221;s assume you take $120/hour for development services. It comes down to $120/hour * 8h/day * 5days/week * 4weeks/month = $ 19.200,00 per month per developer. Which is around $134.400,00 per month for entire 7 people team. In 3 months time this turns out to be $403.200,00 meaning you are not able to spent all of the budget available. Biggest mistake for a project and people on it you can do here is to throw in a few newbies just to fill in the gap for reaching the budget limit. This disrupts the workflow of the rest of the team for two reasons: (a) newbie developers need significant time to get to the level of senior developers thus not being nearly productive as other team members, (b) each team expansion requires extra management input or even change in management philosophy.</p>
<p>What I outlined above usually makes sense in business environment where entire team is working on a new system/platform. Things are significantly different if you alone are trying to create something in your own time (usually as a hobby). In that case we are usually focused on first two topics: (1) Feature list and (2) Development platform selection. Meaning we have no budged to look at, no expected delivery date to worry about.</p>
<p>In my next articles under this topic I will focus strictly on development platform selection and the actual development of web shop from ground up. Until then, I&#8221;ll give you a hint&#8230; Symfony + Zend Framework + Ext JS <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Doctrine DBAL with Symfony2</title>
		<link>http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/</link>
		<comments>http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 10:15:36 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10489</guid>
		<description><![CDATA[I regularly use Doctrine ORM for database operations in my Symfony2 project, but there was one situation that I had to write database importer from SQLITE database into projects Mysql database. Importer should run only once and I didn&#8217;t want &#8230;<p><a href="http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>I regularly use Doctrine ORM for database operations in my Symfony2 project, but there was one situation that I had to write database importer from SQLITE database into projects Mysql database. Importer should run only once and I didn&#8217;t want to make new entity classes for importer, but just make code to work while import is not finished.<span id="more-10489"></span><br />
That case I used Doctrine DBAL  (database abstraction layer).<br />
What we need to use DBAL in Symfony2?</p>
<p>Let&#8217;s start from our main configuration file:</p>
<pre class="brush: php; title: ; notranslate">
#config.yml

#...

# Doctrine Configuration
doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                charset:  UTF8
                driver:   %database_driver%
                host:     %database_host%
                dbname:   %database_name%
                user:     %database_user%
                password: %database_password%
            sqlite:
                driver:  %sqlite_driver%
                path:    %sqlite_path%
    orm:
        auto_generate_proxy_classes: %kernel.debug%
        #auto_mapping: true
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                mappings:
                   SurgeworksAdminBundle: { type: annotation, dir: Entity/ }

#...
</pre>
<p>For Sqlite is necessary just to specify driver and path to database file. I put the database file inside &#8216;app&#8217; folder. My parameters.ini file looks like that:</p>
<pre class="brush: php; title: ; notranslate">
[parameters]
    database_driver=&quot;pdo_mysql&quot;
    database_host=&quot;localhost&quot;
    database_name=&quot;databasename&quot;
    database_user=&quot;someuser&quot;
    database_password=&quot;somepassword&quot;
    mailer_transport=&quot;smtp&quot;
    mailer_host=&quot;localhost&quot;
    mailer_user=&quot;&quot;
    mailer_password=&quot;&quot;
    locale=&quot;en&quot;
    secret=&quot;somesecret&quot;
    sqlite_driver=pdo_sqlite
    sqlite_path=%kernel.root_dir%/sqlite_database_name.db
</pre>
<p>That&#8217;s it from configuration side. Let&#8217;s show how to use it:</p>
<pre class="brush: php; title: ; notranslate">
//...
//Get DBAL connection
//Notice: sqlite_connection is in form: name_connection  - where
//name is connection name defined in config file.
$conn = $this-&gt;getContainer()-&gt;get('doctrine.dbal.sqlite_connection');
$some_array = $conn-&gt;fetchAll('SELECT * FROM yourtablename');
//...
</pre>
<p>And basically, that&#8217;s it.<br />
I always didn&#8217;t wand dealing much with insert strings in sql when you need to add some dynamically created data inside query:</p>
<pre class="brush: php; title: ; notranslate">
// ...
$conn-&gt;exec(“INSERT INTO  sometable (somecolumn ) VALUES (“ . $somevalue . ”)”);
// …
</pre>
<p>What I found very interesting with Doctrine2 DBAL is much cleaner way to do this:</p>
<pre class="brush: php; title: ; notranslate">
            $sql = 'INSERT INTO attributes (
                date_created,
                date_modified
                ) VALUES (?,?)';
            $stmt = $conn_backup-&gt;prepare($sql);
            $stmt-&gt;bindValue(1, $datecreated);
            $stmt-&gt;bindValue(2, $datemodified);
            $stmt-&gt;execute();
</pre>
<p>Of course there is more:</p>
<pre class="brush: php; title: ; notranslate">
 // ..
$conn-&gt;insert('attributes', array('date_created' =&gt; $datecreated));
//..
</pre>
<p>You just have to choose method you like more &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony2 writing data-fixtures</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/#comments</comments>
		<pubDate>Sat, 30 Jul 2011 10:00:21 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10471</guid>
		<description><![CDATA[In last article about fixtures I wrote about manual setup for using data-fixtures with your Symfony2 project. Now it&#8217;s time to write first data fixture. Inside your bundle, create folder called: DataFixtures. We are going to use Doctrine ORM with &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>In last article about fixtures I wrote about manual setup for using data-fixtures with your Symfony2 project.<br />
Now it&#8217;s time to write first data fixture.<span id="more-10471"></span></p>
<p>Inside your bundle, create folder called: DataFixtures.</p>
<p>We are going to use Doctrine ORM with that so create folder inside called &#8216;ORM&#8217;.</p>
<p>Inside that folder create new file called: FixtureLoader.php</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
//Surgeworks\AdminBundle\DataFixtures\ORM\FixtureLoader.php

namespace Surgeworks\AdminBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Surgeworks\AdminBundle\Entity\User;
use Surgeworks\AdminBundle\Entity\Role;
use Surgeworks\AdminBundle\Entity\AttributeType;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

class FixtureLoader implements FixtureInterface {

public function load($manager) {
   $roleSA = new Role();
   $roleSA-&gt;setName('ROLE_SUPER_ADMINISTRATOR');
   $manager-&gt;persist($roleSA);
   $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);

   $user = new User();
   $user-&gt;setFirstName('Darko');
   $user-&gt;setLastName('Goleš');
   $user-&gt;setEmail('darko.goles@surgeworks.com');
   $user-&gt;setUsername('darko.goles');
   $user-&gt;setSalt(md5(time()));
   $password = $encoder-&gt;encodePassword(
       'dont_want_to_tell_you', $user-&gt;getSalt());
   $user-&gt;setPassword($password);
   $user-&gt;getUserRoles()-&gt;add($roleSA);
   $manager-&gt;persist($user);

   $manager-&gt;flush();

}

}
</pre>
<p>Fire up the console, cd to app folder of you project and write:</p>
<pre class="brush: php; title: ; notranslate">

php console doctrine:fixtures:load
</pre>
<p>Command purges the database and inserts fixtures inside.<br />
That&#8217;s it for now,  Cheers <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2 CLI</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-cli/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-cli/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 07:13:49 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10452</guid>
		<description><![CDATA[As someone of you know there is pretty good feature made in Symfony2 that is worth to mention: Console interface with commands that make our life easier to generate different sort of things in our Symfony2 application and execute many &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-cli/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>As someone of you know there is pretty good feature made in Symfony2 that is worth to mention: Console interface with commands that make our life easier to generate different sort of things in our Symfony2 application and execute many useful commands with Doctrine etc.<span id="more-10452"></span></p>
<p>If you want to make some custom feature in your project and that feature is not supposed to be inside your project&#8217;s user interface, than the console commands are right thing for you.</p>
<p>For example, I build some importers from another database to main project&#8217;s database.</p>
<p>It was logically to me that I should use console for importing and not UI where every user can mess up with importer.</p>
<p>To make custom command for Symfony2 CLI, first make new folder inside your bundle called &#8216;command&#8217;.</p>
<p>Inside of that folder we will be creating for each command one php class.<br />
Basic command looks like this:</p>
<pre class="brush: php; title: ; notranslate">
&lt; ?php
namespace Surgeworks\AdminBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ImportCommand extends ContainerAwareCommand {

protected function configure() {

 $this-&gt;setName('importer:import')
      -&gt;setDescription('Import sqllite database into main DOH database')
      -&gt;addArgument('application', InputArgument::REQUIRED, 'What application database you want to import? prayer');
    }

protected function execute(InputInterface $input, OutputInterface $output) {
        $app = $input-&gt;getArgument('application');

        $dialog = $this-&gt;getHelperSet()-&gt;get('dialog');
        $name = $dialog-&gt;ask($output, 'Enter admin username for importing:', '');
        if ($name != 'admin') {
            die('You are not admin! Can\'t let you ruin the database! Sorry...' . &quot;\n&quot;);
        }

        switch ($app) {
            case 'prayers':
                $output-&gt;writeln('Importing &gt;&gt; prayers database ...');
                $this-&gt;ImportPrayers($input, $output);
                break;

            default:
                $output-&gt;writeln('Unknown application name. Please insert one of applications for import');
                break;
        }

    }
</pre>
<p>It is not complicated to make own custom command and make it work.<br />
You just have to write methods what you want to do. Without worry, you can work with database from inside class this way:</p>
<pre class="brush: php; title: ; notranslate">
        //..
        //get em for new tables and entities
        //We may have more entity managers defined in configuration file, so,
        //when calling entity manager write parameter with connection name to get right connection
        $em = $this-&gt;getContainer()-&gt;get('doctrine')-&gt;getEntityManager('default');
        //get connection with sqlite database
        $conn = $this-&gt;getContainer()-&gt;get('doctrine.dbal.sqlite_connection');
        //..
</pre>
<p>After that you just have to open you console and run command from there … <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-cli/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>TWIG with WordPress part1</title>
		<link>http://inchoo.net/wordpress/twig-with-wordpress-part1/</link>
		<comments>http://inchoo.net/wordpress/twig-with-wordpress-part1/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 08:33:22 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Tools]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[theme]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[twig]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9949</guid>
		<description><![CDATA[Making TWIG autoload from WP plugin Maybe someone will say: this is a crazy idea. Why would someone want to do that? Maybe it really is crazy, but I would say: why not? What is TWIG? TWIG is new generation &#8230;<p><a href="http://inchoo.net/wordpress/twig-with-wordpress-part1/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p><strong>Making TWIG autoload from WP plugin</strong></p>
<p><em>Maybe someone will say: this is a crazy idea. Why would someone want to do that?<br />
Maybe it really is crazy, but I would say: why not?<span id="more-9949"></span></em></p>
<p>What is TWIG? TWIG is new generation php templating engine made by Sensio Labs. It is used in their new project Symfony2 as main templating engine provided with framework.<br />
As <a title="TWIG project" href="http://www.twig-project.org/" target="_blank">official page </a> says:</p>
<p><em><strong>Fast:</strong> Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.</em><br />
<em> <strong>Secure:</strong> Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.</em><br />
<em> <strong>Flexible:</strong> Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.</em><br />
It is not necessary to explain in detail why will someone (me) want to use that as wordpress templating engine, but one of the main reasons is that I want to rewrite some messed up php template for WP to better code organized one, and at the and I want it to be with cleaner code as possible.<br />
I don&#8217;t like very much when is necessary to mix up php tags and functions inside HTML code to make it work.<br />
After some thinking about TWIG and how to implement it in my WP installation I got idea:<br />
I will make plug in for WP that will provide all necessary stuff to start using TWIG with WP.</p>
<p>First I created the plugin folder named wp_twig_engine.I put folder named &#8216;<em>lib</em>&#8216; downloaded from<a title="TWIG project site" href="http://www.twig-project.org/" target="_blank"> twig-project site </a> in there. So I had the twig library almost prepared for using.<br />
Now I had to find some appropriate wordpress hook to inject my code into wordpress application logic. After some investigating and testing, I found that it will be possible to use the &#8216;<em>init</em>&#8216; hook and register autoloaders for TWIG library and my custom class in the same function, so I can reach my code from inside template folder later.</p>
<p>Main plugin file: wp-twig.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

/*
  Plugin Name: WordPress Twig templating engine
  Version: 1.0
  Plugin URI: http://inchoo.net
  Description: Engine for creating twig templates for wordpress
  Author: Darko Goleš
  Author URI: http://inchoo.net/author/darko.goles/
 */
//Main twig library autoloader file
require_once dirname(__FILE__) . '/lib/Twig/Autoloader.php';
//My custom class made, I also want it to be autoloaded
require_once dirname(__FILE__) . '/Wp_TwigEngine.php';

function twigAutoLoad() {

    Twig_Autoloader::register();
    Wp_TwigEngine_Autoloader::register();
}

add_action('init', 'twigAutoLoad');
?&gt;
</pre>
<p>Just to show you how to autoload my custom class with that (of course I got idea from original twig autoloader and just changed the code to fit my needs:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
/*
Wp_TwigEngine.php
  Author: Darko Goleš
  Author URI: http://inchoo.net/author/darko.goles/
*/
class Wp_TwigEngine_Autoloader {

    static public function register() {
        ini_set('unserialize_callback_func', 'spl_autoload_call');
        spl_autoload_register(array(new self, 'autoload'));
    }

    static public function autoload($class) {
        if (0 !== strpos($class, 'Wp_TwigEngine')) {
            return;
        }

        if (file_exists($file = dirname(__FILE__) . '/../' . str_replace(array('_', &quot;&#92;&#48;&quot;), array('/', ''), $class) . '.php')) {
            echo($file);
            exit;
            require $file;
        }
    }

}
</pre>
<p>And that&#8217;s it from the plugin side for now. Just have to implement it in the template folder. That is additional theme for another article. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/wordpress/twig-with-wordpress-part1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2 &#8211; Internal server error 500</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-error-500/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-error-500/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 08:04:15 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9929</guid>
		<description><![CDATA[Did you ever had problems with Internal server error 500 with symfony2? I did few days ago. When I open my web application in development mode (http://mysymfony2url/app_dev.php/something) It works OK, but when I tried to open it in &#8216;production&#8217; mode &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-error-500/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>Did you ever had problems with Internal server error 500 with symfony2? I did few days ago. When I open my web application in development mode (http://mysymfony2url/app_dev.php/something) It works OK, but when I tried to open it in &#8216;production&#8217;  mode I always got &#8216;Internal server error 500&#8242; response, so I decided to look at error.log inside my localhost to see what is happening.<br />
Here is what I saw there:<span id="more-9929"></span></p>
<pre class="brush: php; title: ; notranslate">
[Wed Jun 15 15:22:44 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/app/
[Wed Jun 15 15:22:44 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/bin/
[Wed Jun 15 15:22:44 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/src/
[Thu Jun 16 08:11:56 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/app/
[Thu Jun 16 08:11:56 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/bin/
[Thu Jun 16 08:11:56 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/src/
</pre>
<p>There was not enough informations for me to figure out what is wrong with my application.<br />
In development mode it is working just fine, but when I start it in regular (production) mode it returns  an error. I tried to delete cache, refresh page, looked in my config files, but I found nothing.</p>
<p>Then I remembered that recently I upgraded to Symfony2 beta4 version and whole my files except configuration files was overwritten with new ones.</p>
<p><strong>Solution: DO NOT forget to register your bundle namespace inside &#8216;autoload.php&#8217; like I did, otherwise, you can spend few hours to find what is going on without practical solution.<br />
</strong><br />
When I added my namespace inside &#8216;autoload.php&#8217; then  everything was OK.</p>
<pre class="brush: php; title: ; notranslate">

&lt;!--?php use Symfony\Component\ClassLoader\UniversalClassLoader; $loader = new UniversalClassLoader(); $loader---&gt;registerNamespaces(array(
'Symfony'          =&gt; array(__DIR__.'/../vendor/symfony/src', __DIR__.'/../vendor/bundles'),
'Sensio'           =&gt; __DIR__.'/../vendor/bundles',
'JMS'              =&gt; __DIR__.'/../vendor/bundles',
'Doctrine\\Common' =&gt; __DIR__.'/../vendor/doctrine-common/lib',
'Doctrine\\DBAL'   =&gt; __DIR__.'/../vendor/doctrine-dbal/lib',
'Doctrine'         =&gt; __DIR__.'/../vendor/doctrine/lib',
'Monolog'          =&gt; __DIR__.'/../vendor/monolog/src',
'Assetic'          =&gt; __DIR__.'/../vendor/assetic/src',
'Metadata'         =&gt; __DIR__.'/../vendor/metadata/src',
'Surgeworks'         =&gt; __DIR__.'/../src',
));
//...
</pre>
<p>I hope that this post will be helpful to someone with the same problems. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-error-500/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Symfony2 Doctrine2 transactions</title>
		<link>http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/</link>
		<comments>http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/#comments</comments>
		<pubDate>Tue, 31 May 2011 08:38:40 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Database transactions]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Doctrine2]]></category>
		<category><![CDATA[Doctrine2 transactions]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[symfony2]]></category>
		<category><![CDATA[Transactions]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9687</guid>
		<description><![CDATA[Like everything else, using transactions in Symfony2 is easy task. I had a case that I had to use transactions to make sure that everything or none is saved to database, because I didn&#8217;t wand anything to break at the &#8230;<p><a href="http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Like everything else, using transactions in Symfony2 is easy task.<br />
I had a case that I had to use transactions to make sure that everything or none is saved to database, because I didn&#8217;t wand anything to break at the half way and leave data unsaved.<span id="more-9687"></span>There are two basic different ways to use transactions with Doctrine 2. In official documentation there is one approach suggested for transactions, but if you find necessary like I did, use second one. The important thing is not to forget rollback in your code if you are using approach that is not suggested.</p>
<p style="text-align: justify;">Example from Doctrine2 official documentation:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
// $em instanceof EntityManager
$em-&gt;transactional(function($em) {
    //... do some work
    $user = new User;
    $user-&gt;setName('George');
    $em-&gt;persist($user);
});
</pre>
<p style="text-align: justify;">I found this approach inconvenient for my code because variables defined outside transactional function are not accessible directly and I had many variables defined in my controller action and didn&#8217;t want to refractor all the code. Because of that I used the second possibility in my code:</p>
<pre class="brush: php; title: ; notranslate">

    /**
     * @Route(&quot;/admin/tags/ajax_save_new_tag&quot;, name=&quot;_admin_tags_ajax_save_new_tag&quot;)
     */
    public function ajaxSaveNewTagAction() {

        $request = $this-&gt;get('request');
        $isAjax = $request-&gt;isXmlHttpRequest();

        /* BEGIN If is ajax call... */
        if ($isAjax == true) {

            $em = $this-&gt;get('doctrine.orm.entity_manager');
            $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();
            $userId = $user-&gt;getId();
            $localizations = '';
            $tagname = '';

            if (isset($_POST['localization']))
                $localizations = $_POST['localization'];

            if (isset($_POST['tag']['tag_name']))
                $tagname = $_POST['tag']['tag_name'];

            $tag = new \Surgeworks\AdminBundle\Entity\Tag();
            $tag-&gt;setTagName($tagname);

            $tag-&gt;setUserId($userId);

            $q = $em-&gt;createQuery(&quot;select max(a.sort_order) from Surgeworks\AdminBundle\Entity\Tag a&quot;);
            $maxorder = $q-&gt;getSingleScalarResult();

            if (null === $maxorder) {
                $maxorder = 0;
            }
            $tmp = $maxorder - ($maxorder % 10);
            $tag-&gt;setSortOrder($tmp + 10);

            $validator = $this-&gt;container-&gt;get('validator');
            $errorList = $validator-&gt;validate($tag);

            $msg = &quot;&quot;;
            if (count($errorList) &gt; 0) {
                foreach ($errorList as $err) {
                    $msg.= $err-&gt;getMessage() . &quot;\n&quot;;
                }
                return new Response($msg, '400');
            }

            /*             * ******** BEGIN TRANSACTION ******** */
            $em-&gt;getConnection()-&gt;beginTransaction();
            try {

                $em-&gt;persist($tag);
                $em-&gt;flush();

                if (!empty($localizations)) {
                    foreach ($localizations as $langsymbol =&gt; $tagname) {

                        $loc = new \Surgeworks\AdminBundle\Entity\TagLocalization();
                        $loc-&gt;setTagId($tag-&gt;getId());
                        $loc-&gt;setLanguageSymbol($langsymbol);
                        $loc-&gt;setTagTitle($tagname[0]);
                        $loc-&gt;setUserId($userId);

                        $errorList = $validator-&gt;validate($loc);

                        $msg = &quot;&quot;;
                        if (count($errorList) &gt; 0) {
                            foreach ($errorList as $err) {
                                $msg.= $err-&gt;getMessage() . &quot;\n&quot;;
                            }
                            return new Response($msg, '400');
                        }

                        $em-&gt;persist($loc);
                        $em-&gt;flush();
                    }
                }

                $em-&gt;getConnection()-&gt;commit();
                $msg = &quot;Tag saved successfully!&quot;;
                $code = &quot;OK&quot;;
            } catch (\Exception $e) {

                $em-&gt;getConnection()-&gt;rollback();
                $em-&gt;close();
                throw $e;
            }

            //get languages list for select box
            $languages = $em-&gt;getRepository('Surgeworks\AdminBundle\Entity\Language')-&gt;findAll();

            $langsarr = array();

            foreach ($languages as $val) {

                array_push($langsarr, array('langsymbol' =&gt; $val-&gt;getLanguageSymbol(), 'langname' =&gt; $val-&gt;getLanguageName()));
            }

            $response = new Response(json_encode(array('langlist' =&gt; $langsarr)), '200');
            $response-&gt;headers-&gt;set('Content-Type', 'application/json');

            return $response;
        }
        //If not ajax call
        return new Response('Silence is golden');
    }
</pre>
<p>As I sad: don&#8217;t forget to write rollback when you are using this approach. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Symfony2 Forms &#8211; Entity field type</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-entity-field-type/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-entity-field-type/#comments</comments>
		<pubDate>Tue, 31 May 2011 06:59:32 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Entity type]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9674</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 Beta3. Might not work on later releases! Symfony2 offers many prebuilt field types for using when creating forms. The one of them I found interesting is &#8216;EntityType&#8217;. There are just basic documentation about that. I had &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-entity-field-type/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;"><strong>NOTE: Tested on Symfony2 Beta3. Might not work on later releases!</strong></p>
<p style="text-align: justify;">Symfony2 offers many prebuilt field types for using when creating forms. The one of them I found interesting is &#8216;EntityType&#8217;. <a title="Entity field type" href="http://symfony.com/doc/current/reference/forms/types/entity.html" target="_blank">There are just basic documentation about that</a>.</p>
<p style="text-align: justify;">I had one case recently that I had to use Entity field type for creating form, but except using it in simple way like documented I wanted to use it on little more advanced way.<span id="more-9674"></span>I have table in database called statuses that have basic filelds like:</p>
<p style="text-align: justify;">id (int11), status_name (varchar 50), status_type (varchar 20). I defined 3 basic statuses that will be used for all items I have to describe their state:</p>
<p style="text-align: justify;"><em>draft, live, deleted</em></p>
<p style="text-align: justify;">but, also I have more statuses defined that is for other purposes.</p>
<p style="text-align: justify;">Because of that I defined these three types to have status type &#8216;<em>basic</em>&#8216; and I wanted to create form with select box, but only <em>filter and show these three statuses and ignore others</em>.</p>
<p style="text-align: justify;">For that purpose, I used &#8216;<em>Entity</em>&#8216; field type, but I don&#8217;t want to pull all statuses from database, but only those three that have defined status_type: &#8216;<em>basic</em>&#8216;.</p>
<p>Here is the code:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
//Surgeworks/AdminBundle/Forms/ItemForm.php
namespace Surgeworks\AdminBundle\Forms;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class Itemform extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {

        $builder-&gt;add('item_type','entity', array('class'=&gt;'Surgeworks\AdminBundle\Entity\ItemType', 'property'=&gt;'item_type_name', ));
        $builder-&gt;add('item_status','entity', array('class'=&gt;'Surgeworks\AdminBundle\Entity\Status', 'property'=&gt;'status_name',
            'query_builder' =&gt; function (\Surgeworks\AdminBundle\Entity\StatusRepository $repository)
            {return $repository-&gt;createQueryBuilder('s')-&gt;where('s.status_type = ?1')-&gt;setParameter(1, 'basic')-&gt;add('orderBy', 's.sort_order ASC');} ));
        $builder-&gt;add('item_name');

    }
    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' =&gt; 'Surgeworks\AdminBundle\Entity\Item',
        );
    }
}
</pre>
<p>when we ignore rest of the code here is how to use it inside function:</p>
<pre class="brush: php; title: ; notranslate">
        $builder-&gt;add('item_status',
                      'entity',
                       array(
                             'class'=&gt;'Surgeworks\AdminBundle\Entity\Status',
                             'property'=&gt;'status_name',
                             'query_builder' =&gt; function (\Surgeworks\AdminBundle\Entity\StatusRepository $repository)
                             {
                                 return $repository-&gt;createQueryBuilder('s')
                                        -&gt;where('s.status_type = ?1')
                                        -&gt;setParameter(1, 'basic')
                                        -&gt;add('orderBy', 's.sort_order ASC');
                             }
                            )
                      );
</pre>
<p>This is basic example how to use query_builder option with entity field type for creating forms.I hope you enjoyed the post and found it helpful.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-entity-field-type/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Symfony2 from beta1 to beta2</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/#comments</comments>
		<pubDate>Tue, 24 May 2011 11:20:03 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9399</guid>
		<description><![CDATA[Today I had to migrate existing project from Symfony2 Beta 1 version to Beta2. First I looked at the difference between my config files and new one provided with Beta2.After some minor changes to config files, when I tried to &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>Today I had to migrate existing project from Symfony2 Beta 1 version to Beta2.<br />
First I looked at the difference between my config files and new one provided with Beta2.<span id="more-9399"></span>After some minor changes to config files, when I tried to start project in browser to see possible errors, I see not so happy surprise:</p>
<p>Annotation syntax in controllers and models are no longer working for me this way.<br />
After some digging into code and official Symfony2 documentation here is what I found:</p>
<p>1. In controllers, instead of:</p>
<pre class="brush: php; title: ; notranslate">

    /**
     * @extra:Route(&quot;/admin/applications&quot;, name=&quot;_admin_applications&quot;)
     * @extra:Template()
     */
</pre>
<p>It has to be written like that:</p>
<pre class="brush: php; title: ; notranslate">

    /**
     * @Route(&quot;/admin/applications&quot;, name=&quot;_admin_applications&quot;)
     * @Template()
     */
</pre>
<p>2. Don&#8217;t forget to add these two lines on the top of each controller:</p>
<pre class="brush: php; title: ; notranslate">

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
</pre>
<p>3. In entities, instead of:</p>
<pre class="brush: php; title: ; notranslate">

/**
 * @orm:Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\AttributeTypeRepository&quot;)
 * @orm:Table(name=&quot;attribute_types&quot;)
 */
class AttributeType {

    /**
     * @orm:Id
     * @orm:Column(type=&quot;integer&quot;)
     * @orm:GeneratedValue(strategy=&quot;AUTO&quot;)
     */
    protected $id;
</pre>
<p>It should be like:</p>
<pre class="brush: php; title: ; notranslate">

/**
 * @ORM\Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\AttributeTypeRepository&quot;)
 * @ORM\Table(name=&quot;attribute_types&quot;)
 */
class AttributeType {

    /**
     * @ORM\Id
     * @ORM\Column(type=&quot;integer&quot;)
     * @ORM\GeneratedValue(strategy=&quot;AUTO&quot;)
     */
    protected $id;
</pre>
<p>4. Don&#8217;t forget to add this line on the top of each entity:</p>
<pre class="brush: php; title: ; notranslate">

use Doctrine\ORM\Mapping as ORM;
</pre>
<p>Also I used some annotations like this in my entity:</p>
<pre class="brush: php; title: ; notranslate">

     * @assert:Type(type=&quot;Surgeworks\AdminBundle\Entity\Status&quot;)

    protected $item_status;
</pre>
<p>but, this also is not working anymore, and instead of this it shoul be like this:</p>
<pre class="brush: php; title: ; notranslate">

     * @Assert\Type(type=&quot;Surgeworks\AdminBundle\Entity\Status&quot;)
</pre>
<p>Of course, we should add one more line on the top to get all the thing work:</p>
<pre class="brush: php; title: ; notranslate">

use Symfony\Component\Validator\Constraints as Assert;
</pre>
<p>That was just short tutorial for fast migration from Symfony2 beta1 version to Symfony2 Beta 2 version.</p>
<p>I hope in the future they will not add so many changes in the core framework, because every time new version is out, I have to loose few hours to upgrade. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>PS. Don&#8217;t forget to clear all cache before testing.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony2 – validation part 1</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-validation-part-1/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-validation-part-1/#comments</comments>
		<pubDate>Fri, 20 May 2011 07:59:30 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9331</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 Beta1. Might not work on later releases! Few days ago I tried to find validation method for duplicate items in database because I have a table named &#8216;languages&#8217; and need &#8216;language_symbol&#8217; field to be unique. In &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-validation-part-1/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 Beta1. Might not work on later releases!</strong></p>
<p>Few days ago I tried to find validation method for duplicate items in database because I have a table named &#8216;languages&#8217; and need &#8216;language_symbol&#8217; field to be unique.</p>
<p><span id="more-9331"></span></p>
<p>In my entity named Language.php it is written like this:</p>
<pre class="brush: php; title: ; notranslate">
    /**
     * @orm:Column(type=&quot;string&quot;, length=&quot;10&quot;, unique=true)
     */
    protected $language_symbol;

//..
</pre>
<p>I also have a form with field &#8216;language_symbol&#8217; and need to validate for duplicated entry.<br />
Except I can do it with the AJAX, I didn&#8217;t want to and tried to validate with native Symfony2 validation.<br />
Here is how I did this:<br />
I added a validation function inside Entity: &#8216;Language.php&#8217;:</p>
<pre class="brush: php; title: ; notranslate">
//Surgeworks/AdminBundle/Entity/Language.php
//..
    public function isSymbolDuplicated()
    {
$q = $this-&gt;em-&gt;createQuery(&quot;SELECT count(l.id) FROM Surgeworks\AdminBundle\Entity\Language l WHERE (l.language_symbol='&quot; . $this-&gt;language_symbol . &quot;' AND l.id &lt;&gt; '&quot;.$this-&gt;id.&quot;')&quot;);
        $result = $q-&gt;getSingleScalarResult();
        return $result==1?true:false;
    }
//..
</pre>
<p>Also, I have to put variable to pass entity manager reference to my &#8216;Language.php&#8217; class so I could make database calls. <em>I know that it was not maybe the best way to implement that, but it was the fastest way to get it work.</em></p>
<pre class="brush: php; title: ; notranslate">
/**
 * @orm:Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\LanguageRepository&quot;)
 * @orm:Table(name=&quot;languages&quot;)
 */
class Language{

    /**
     * @orm:Id
     * @orm:Column(type=&quot;integer&quot;)
     * @orm:GeneratedValue(strategy=&quot;AUTO&quot;)
     */
      protected $id;
      protected $em;

    public function setEm($em) {
        $this-&gt;em = $em;
    }
//..
</pre>
<p>After that, in my controller I put this:</p>
<pre class="brush: php; title: ; notranslate">
/**
     * @extra:Route(&quot;/admin/languages/add_new&quot;, name=&quot;_admin_languages_add&quot;)
     * @extra:Template
     */
    public function addAction() {

        $em = $this-&gt;get('doctrine.orm.entity_manager');
        $language = new \Surgeworks\AdminBundle\Entity\Language();
	 //Sst reference to entity manager so it can be used in entity class directly for validation purposes
        $language-&gt;setEm($em);
</pre>
<p>And, here is how my &#8216;validation.yml&#8217; looks like:</p>
<pre class="brush: php; title: ; notranslate">
Surgeworks\AdminBundle\Entity\Language:
    properties:
        language_name:
            - NotBlank: { message: &quot;Language name field can not be empty!&quot; }
            #- NotBlank: ~
        language_symbol:
            - NotBlank: { message: &quot;Language symbol field can not be empty!&quot; }
    getters:
        SymbolDuplicated:
            - 'False': { message: &quot;Language symbol must be unique.You entered symbol that already exist in database!&quot; }
</pre>
<p><em><strong>Just one important note: If you look in Symfony2 documentation about true , false validation Constraints you will see that in above source I put the word true in single quotes. If you do not it will generate error, so I thing that it should be properly written in official Symfony2 documentation page which is not the case now.</strong></em><br />
That&#8217;s it about validation for now. I am sure that I will make more posts about it in the near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-validation-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony 2 paginator &#8211; improved version</title>
		<link>http://inchoo.net/tools-frameworks/paginator-symfony2-beta/</link>
		<comments>http://inchoo.net/tools-frameworks/paginator-symfony2-beta/#comments</comments>
		<pubDate>Fri, 20 May 2011 07:03:17 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[pagination]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[symfony2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9313</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 Beta3. Might not work on later releases! After some comments on forums about my earlier post: “Custom Pagination in Symfony 2” that was made on Symfony2 version: PR 12, I decided to make some changes in &#8230;<p><a href="http://inchoo.net/tools-frameworks/paginator-symfony2-beta/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 Beta3. Might not work on later releases! </strong></p>
<p>After some comments on forums about my earlier post:<br />
<a href="http://inchoo.net/tools-frameworks/symfony-2-pagination/">“Custom Pagination in Symfony 2”</a> that was made on Symfony2 version: PR 12,<br />
I decided to make some changes in the source code and give it available for download.</p>
<p>Basic structure of paginator is similar to latest post, but improvements are made by removing HTML stuff from controller, so paginator is rendered by twig template and not  inside class on the fly.<span id="more-9313"></span>There are some more things that could be improved, for example:<br />
I didn&#8217;t add some forward – backward arrow – links into displayed paginator and also didn&#8217;t limit number of links that will be shown, and I do not intend to.</p>
<p><em>If anybody  thinks that it has to be improved more, fixed or something else, feel free to do it yourself.</em></p>
<p>Let&#8217;s show how to use it:</p>
<p>First, put class Paginator.php somewhere inside your Bundle. I put it into Helpers folder. Just rename namespace defined inside class to your own.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * Paginator.php
 * Class to generate pagination for items
 *
 * @author Darko Goleš
 * @www.inchoo.net
 */
//Here replace namespace, depends where you put yours :
namespace Surgeworks\AdminBundle\Helpers;
class Paginator {
//..
</pre>
<p>Before using it, just to take a look into the constructor for a moment:</p>
<pre class="brush: php; title: ; notranslate">
//..
    function __construct($itemscount, $currenturl, $options=array(10,20,30,50,100,500)) {
        //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;getInternalNumPages();
        //Calculate first shown item on current page
        $this-&gt;calculateOffset();

        $this-&gt;currentUrl = $currenturl;

        $this-&gt;options = $options;
    }
//..&lt;/pre&gt;
&lt;pre&gt;</pre>
<p>Why we looked into the constructor now? To see that there is third, optional argument that takes array of numbers with some predefined values. That is for: “how many items to show” list purpose.<br />
In controller, when you use it, you can define custom values that will be shown in the select list (10, 20, 500). Also, <strong>you may not define &#8216;show All&#8217;</strong> because that is already predefined in the twig template, so as this parameter, <strong>use only array of number</strong>s.</p>
<p>Let&#8217;s take a look how to use it in the controller:</p>
<pre class="brush: php; title: ; notranslate">
    /**
     * @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, $this-&gt;generateUrl('_admin_languages'));
        //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';

            $this-&gt;get('session')-&gt;set('lang_list_order_by', $order_by);
            $this-&gt;get('session')-&gt;set('lang_list_sort_dir', $sort_direction);
        } else {

            if ($this-&gt;get('session')-&gt;get('lang_list_order_by') != null) {
                $order_by = $this-&gt;get('session')-&gt;get('lang_list_order_by');
            } else {
                $order_by = array('sort_order' =&gt; 'asc', 'id' =&gt; 'asc');
            }
            if ($this-&gt;get('session')-&gt;get('lang_list_sort_dir') != null) {
                $sort_direction = $this-&gt;get('session')-&gt;get('lang_list_sort_dir');
            } else {
                $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; $paginator);
    }
</pre>
<p>Of course, you need to make some function in LanguagesRepository  to get count of items for paginator.</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>Don&#8217;t forget to add this repository class to Entity class:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Surgeworks\AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @orm:Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\LanguageRepository&quot;)
 * @orm:Table(name=&quot;languages&quot;)
 */
class Language{
//..
</pre>
<p>After all of that is done, put paginator.html.twig inside Resources/views/Somewhere  (I put in Resources/views/Global/ folder).<br />
Let&#8217;s render it in twig template:</p>
<pre class="brush: php; title: ; notranslate">
 {% include 'SurgeworksAdminBundle:Global:paginator.html.twig' %}
</pre>
<p>That&#8217;s all about paginator for now. <a href="http://inchoo.net/wp-content/uploads/2011/05/Paginator.zip">Here you can download Symfony2 paginator files</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/paginator-symfony2-beta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony 2 forms validation</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-validation-forms/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-validation-forms/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 07:31:38 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[project]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9172</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 PR12. Might not work on later releases! To continue previous article when writing about forms in Symfony 2, now it&#8217;s time to write something about forms validation. In the previous article, we created a form like &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony2-validation-forms/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 PR12. Might not work on later releases!</strong></p>
<p>To continue previous article when writing about forms in Symfony 2, now it&#8217;s time to write something about forms validation.<span id="more-9172"></span></p>
<p>In <a href="http://inchoo.net/tools/symfony-2-forms/">the previous article</a>, we created a form like this:</p>
<pre class="brush: php; title: ; notranslate">
&amp;lt;?php
//Surgeworks/AdminBundle/Forms/LanguageForm.php

namespace Surgeworks\AdminBundle\Forms;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\TextField;
use Symfony\Component\Form\HiddenField;

//form for Create and update information about languages
class LanguageForm extends Form{

    protected function configure() {
        $this-&amp;gt;add(new TextField('language_name',  array('max_length'=&amp;gt;50, 'required' =&amp;gt; true)));
        $this-&amp;gt;add(new TextField('language_symbol',  array('max_length'=&amp;gt;10, 'required' =&amp;gt; true)));
        $this-&amp;gt;addOption('name', 'adminForm');
    }
}
</pre>
<p>Now we need to validate these two fields for entering new record into database when form is submitted. This is done by creating new file called &#8216;validation.yml&#8217;. Of course you have more possibility to create that file like the other configuration files either in xml or plain php. But for purposes of article let&#8217;s make it in yaml.</p>
<pre class="brush: php; title: ; notranslate">
//Surgeworks/AdminBundle/Resources/config/validation.yml
Surgeworks\AdminBundle\Entity\Language:  //enter name of your entity to validate against
    properties:
        language_name:
            - NotBlank: { message: &amp;quot;Language name field can not be empty!&amp;quot; }
        language_symbol:
            - NotBlank: { message: &amp;quot;Language symbol field can not be empty!&amp;quot; }
</pre>
<p>After all &#8216;hard work&#8217; is done, let&#8217;s tell to our controller action to validate that form:<br />
(Using same controller from last article)</p>
<pre class="brush: php; title: ; notranslate">
//…
    public function addAction() {
	//Creating form's instance
        $form = LanguageForm::create($this-&amp;gt;get('form.context'), 'adminForm');
//...

//Binding form to entity...
$form-&amp;gt;bind($request, $language);

//...

	//If our form passes validation
            if ($form-&amp;gt;isValid()) {

	    //We already made bind to entity, just need to save data into database
                $em-&amp;gt;persist($language);
                $em-&amp;gt;flush();
	 //Now it's time to redirect to some url when data is saved...
                return new RedirectResponse($this-&amp;gt;generateUrl('_admin_languages'));
}

//...
</pre>
<p>Of course, until now, I didn&#8217;t mention:<br />
what about AJAX?<br />
If we send form&#8217;s data in some AJAX form, can we validate this way?</p>
<p>There is also solution for AJAX too:</p>
<p>First we need to determine type of request received in our controller:</p>
<pre class="brush: php; title: ; notranslate">
//...

$request = $this-&amp;gt;get('Request');
            $isAjax = $request-&amp;gt;isXmlHttpRequest();//if true – then AJAX is used

//..
</pre>
<p>Now when we know is that AJAX request we could write AJAX validation handling part:</p>
<pre class="brush: php; title: ; notranslate">
//Our controller file

/* BEGIN If is ajax call... */
            if ($isAjax == true) {

                $validator = $this-&amp;gt;container-&amp;gt;get('validator');
                $errorList = $validator-&amp;gt;validate($language);

                $msg = &amp;quot;&amp;quot;;
                if (count($errorList) &amp;gt; 0) {
                    foreach ($errorList as $err) {
                        $msg.= $err-&amp;gt;getMessage() . &amp;quot;\n&amp;quot;;
                    }
                    $code = &amp;quot;ERR&amp;quot;;
                } else {
                    $em-&amp;gt;persist($language);
                    $em-&amp;gt;flush();
                    $msg = &amp;quot;Language saved successfully!&amp;quot;;
                    $code = &amp;quot;OK&amp;quot;;
                }
                $response = new Response(json_encode(array('code' =&amp;gt; $code, 'msg' =&amp;gt; $msg)));
                $response-&amp;gt;headers-&amp;gt;set('Content-Type', 'application/json');

                return $response;
            }
</pre>
<p>Let me explain what I did here: First of all, we get validator service, and then get list of errors if any by validating our Entity instance with validator service. (variable &#8216;$language&#8217; is our entity instance).</p>
<p>Then we loop through possible errors and adding error message to variable $msg.  Also, I predefined two possible response messages for AJAX response: “ERR” and “OK” and I am handling it in my AJAX function on the client side. So, when return $code and $message are defined depends if we have errors or not, let&#8217;s just return response to our AJAX function in JSON form for easy processing with our Javascript on client side. (We shouldn&#8217;t forget to set response headers to application/json).</p>
<p>To all of these get work, we need to do one more thing:</p>
<pre class="brush: php; title: ; notranslate">
framework:
    validation:    { enabled: true, annotations: false }
</pre>
<p>Add, or check if exists this into your main config.yml file of application and also make sure if you are using validation this way, that annotations are false. If you are using annotations for validation, don&#8217;t forget to set it to true here.</p>
<p>This is all for now. BTW, yesterday I looked in official documentation and find out that will be some new ways, let&#8217;s say different ways for using forms in project in first beta release of Symfony 2, and when that release is available to me, I will write more about forms in new way of handling it.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-validation-forms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony 2 Form</title>
		<link>http://inchoo.net/tools-frameworks/symfony-2-forms/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony-2-forms/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 13:24:07 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[cms]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9153</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 PR12. Might not work on later releases! If you want to use forms in Symfony 2 project there is already prepared system for that. First in &#8216;Yourname/SomethingBundle/Forms&#8217; folder create class like this: then the form is &#8230;<p><a href="http://inchoo.net/tools-frameworks/symfony-2-forms/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 PR12. Might not work on later releases!</strong></p>
<p>If you want to use forms in Symfony 2 project there is already prepared system for that.</p>
<p>First in &#8216;Yourname/SomethingBundle/Forms&#8217; folder create class like this:<span id="more-9153"></span></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Surgeworks\AdminBundle\Forms;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\TextField;
use Symfony\Component\Form\HiddenField;

//form for Create and update information about languages
class LanguageForm extends Form{

    protected function configure() {
        $this-&gt;add(new TextField('language_name',  array('max_length'=&gt;50, 'required' =&gt; true)));
        $this-&gt;add(new TextField('language_symbol',  array('max_length'=&gt;10, 'required' =&gt; true)));
        $this-&gt;addOption('name', 'adminForm');
    }
}
</pre>
<p>then the form is ready for using inside controller:</p>
<pre class="brush: php; title: ; notranslate">
    /**
     * @extra:Route(&quot;/admin/languages/add_new&quot;, name=&quot;_admin_languages_add&quot;)
     * @extra:Template
     */
    public function addAction() {

        $form = LanguageForm::create($this-&gt;get('form.context'), 'adminForm');
</pre>
<p>After that in the same controller action bind form to your existing Entity:</p>
<pre class="brush: php; title: ; notranslate">
$request = $this-&gt;get('Request');
            $form-&gt;bind($request, $language);
</pre>
<p>Attention:  make sure that form field names is same like your Entity properties names!</p>
<p>One little tip: When field names in Entity class contain _ (underscore) character, make sure to remove that character in setter and getter function names, for example:</p>
<pre class="brush: php; title: ; notranslate">
//contains underscore character like fieldname in database
protected $status_id;
//theese methods must be without that character
    public function getStatusId() {
        return $this-&gt;status_id;
    }
    public function setStatusId($status_id) {
        $this-&gt;status_id = $status_id;
    }
</pre>
<p>For displaying form in the template there are several ways, end one of them is:</p>
<pre class="brush: php; title: ; notranslate">
        &lt;form action=&quot;#&quot; method=&quot;post&quot; id=&quot;adminForm&quot; enctype=&quot;application/x-www-form-urlencoded&quot;&gt;
    {{ form_errors(form) }}
    {% for field in form %}
        {% if not field.ishidden %}
            &lt;div class=&quot;formitem&quot;&gt;
            {{ form_errors(field) }}
            {{ form_label(field) }}
            {{ form_field(field) }}
            &lt;/div&gt;
        {% endif %}
    {% endfor %}
{{ form_hidden(form) }}
                &lt;input type=&quot;submit&quot; value=&quot;submit&quot;/&gt;
        &lt;/form&gt;
</pre>
<p>In the next article of Symfony 2 series I will write about validating form&#8217;s data in Symfony 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony-2-forms/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to add new custom category attribute in Magento</title>
		<link>http://inchoo.net/ecommerce/magento/how-to-add-new-custom-category-attribute-in-magento/</link>
		<comments>http://inchoo.net/ecommerce/magento/how-to-add-new-custom-category-attribute-in-magento/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 13:56:31 +0000</pubDate>
		<dc:creator>Vedran Subotic</dc:creator>
				<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Integration]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=8898</guid>
		<description><![CDATA[Sometimes you need to extend functionality of Magento categories. There is several ways to do that, I will show you how it can be done. You can do that by modifying and adding data into some of tables directly, but &#8230;<p><a href="http://inchoo.net/ecommerce/magento/how-to-add-new-custom-category-attribute-in-magento/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to extend functionality of Magento categories. There is several ways to do that, I will show you how it can be done.<br />
You can do that by modifying and adding data into some of tables directly, but it can be waste of time if you don&#8217;t know what you are doing.<br />
This post will describe how you can add new custom category attribute in your Magento store via sql_setup script.</p>
<p><span id="more-8898"></span></p>
<p>MySQL setup script will look something like this, it depends on your needs and how you would like to configure your new attribute:</p>
<pre class="brush: php; title: ; notranslate">
$installer = $this;
$installer-&gt;startSetup();

$entityTypeId     = $installer-&gt;getEntityTypeId('catalog_category');
$attributeSetId   = $installer-&gt;getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $installer-&gt;getDefaultAttributeGroupId($entityTypeId, $attributeSetId);

$installer-&gt;addAttribute('catalog_category', 'new_cat_attrb',  array(
    'type'     =&gt; 'int',
    'label'    =&gt; 'New Category Attribute',
    'input'    =&gt; 'text',
    'global'   =&gt; Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'           =&gt; true,
    'required'          =&gt; false,
    'user_defined'      =&gt; false,
    'default'           =&gt; 0
));

$installer-&gt;addAttributeToGroup(
    $entityTypeId,
    $attributeSetId,
    $attributeGroupId,
    'new_cat_attrb',
    '11'					//last Magento's attribute position in General tab is 10
);

$attributeId = $installer-&gt;getAttributeId($entityTypeId, 'new_cat_attrb');

$installer-&gt;run(&quot;
INSERT INTO `{$installer-&gt;getTable('catalog_category_entity_int')}`
(`entity_type_id`, `attribute_id`, `entity_id`, `value`)
    SELECT '{$entityTypeId}', '{$attributeId}', `entity_id`, '1'
        FROM `{$installer-&gt;getTable('catalog_category_entity')}`;
&quot;);

//this will set data of your custom attribute for root category
Mage::getModel('catalog/category')
    -&gt;load(1)
    -&gt;setImportedCatId(0)
    -&gt;setInitialSetupFlag(true)
    -&gt;save();

//this will set data of your custom attribute for default category
Mage::getModel('catalog/category')
    -&gt;load(2)
    -&gt;setImportedCatId(0)
    -&gt;setInitialSetupFlag(true)
    -&gt;save();

$installer-&gt;endSetup();
</pre>
<p>In your config.xml file of your module you will need to add this part in order to install correctly your new category attribute:</p>
<pre class="brush: php; title: ; notranslate">
&lt;resources&gt;
	&lt;new_attribute_csv_setup&gt;
	  &lt;setup&gt;
		&lt;module&gt;New_Attribute&lt;/module&gt;
		&lt;class&gt;Mage_Catalog_Model_Resource_Eav_Mysql4_Setup&lt;/class&gt;
	  &lt;/setup&gt;
	  &lt;connection&gt;
		&lt;use&gt;core_setup&lt;/use&gt;
	  &lt;/connection&gt;
	&lt;/new_attribute_setup&gt;
	&lt;new_attribute_setup_write&gt;
	  &lt;connection&gt;
		&lt;use&gt;core_write&lt;/use&gt;
	  &lt;/connection&gt;
	&lt;/new_attribute_setup_write&gt;
	&lt;new_attribute_setup_read&gt;
	  &lt;connection&gt;
		&lt;use&gt;core_read&lt;/use&gt;
	  &lt;/connection&gt;
	&lt;/new_attribute_setup_read&gt;
&lt;/resources&gt;
</pre>
<p>Pay attention on class tag here, class must be: &#8220;Mage_Catalog_Model_Resource_Eav_Mysql4_Setup&#8221;.</p>
<p>If you did this correctly, you will get something like this:<br />
<a href="http://inchoo.net/wp-content/uploads/2011/03/new_category_attribute.png"><img src="http://inchoo.net/wp-content/uploads/2011/03/new_category_attribute-600x321.png" alt="" title="new_category_attribute" width="600" height="321" class="alignleft size-medium wp-image-8900" /></a></p>
<p>Enjoy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/how-to-add-new-custom-category-attribute-in-magento/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		</item>
		<item>
		<title>Unit testing with Zend framework: Setting up environment for the first test using Netbeans IDE for php</title>
		<link>http://inchoo.net/tools-frameworks/unit-testing-with-zend-framework-setting-up-environment-for-the-first-test-using-netbeans-ide-for-php/</link>
		<comments>http://inchoo.net/tools-frameworks/unit-testing-with-zend-framework-setting-up-environment-for-the-first-test-using-netbeans-ide-for-php/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 14:49:49 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[Zend]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[project]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=8862</guid>
		<description><![CDATA[Assuming that you already installed PHPUnit because there are already many tutorials about that, I will write just one short tutorial about setting up test environment for Zend application. I am currently using windows 7, and NetBeans IDE for php &#8230;<p><a href="http://inchoo.net/tools-frameworks/unit-testing-with-zend-framework-setting-up-environment-for-the-first-test-using-netbeans-ide-for-php/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>Assuming that you already installed PHPUnit because there are already many tutorials about that, I will write just one short tutorial about setting up test environment for Zend application. I am currently using windows 7, and NetBeans IDE for php 6.9.1. <span id="more-8862"></span>First we have to setup some PHPUnit options in NetBeans, so go to:<br />
<strong>Tools -&gt; Options -&gt; Php -&gt; Unit Testing</strong><br />
and click on Browse and choose location of your installed PHPUnit script (phpunit.bat) which is often located in php – installation folder and click OK to confirm selection.</p>
<p><img class="alignleft size-full wp-image-8863" title="NB_PHPUnit_001" src="http://inchoo.net/wp-content/uploads/2011/03/NB_PHPUnit_001.jpg" alt="" width="600" height="446" /></p>
<p>Now we can create new Php project based on Zend framework, or open some existing Zend project in which we will write our first test. In NB I am using Zend tool integration to generate first project sources.</p>
<p>When the project is opened/created, in projects window right click on project name and choose <strong>Properties.</strong><br />
After the project properties window is opened, click on PHPUnit category on the left side, and on the right of the window we can see PHPUnit configuration options. For this tutorial, let&#8217;s select “Use bootstrap” option and click “Generate” button on the right, so new bootstrap.php file is generated inside folder “tests” of our Zend application.<img class="alignleft size-full wp-image-8864" title="NB_PHPUnit_002" src="http://inchoo.net/wp-content/uploads/2011/03/NB_PHPUnit_002.jpg" alt="" width="600" height="434" /></p>
<p>In that file we will put all basic configuration for our application testing and necessary include paths like this:</p>
<p><em>bootstrap.php</em></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
error_reporting( E_ALL | E_STRICT );
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
define('APPLICATION_ENV', 'testing');
define('LIBRARY_PATH', realpath(dirname(__FILE__) . '/../library'));
define('TESTS_PATH', realpath(dirname(__FILE__)));

$_SERVER['SERVER_NAME'] = 'http://cea.local';

$includePaths = array(LIBRARY_PATH, get_include_path());
set_include_path(implode(PATH_SEPARATOR, $includePaths));

require_once &quot;Zend/Loader/Autoloader.php&quot;;

$loader = Zend_Loader_Autoloader::getInstance();
$loader-&gt;setFallbackAutoloader(true);
$loader-&gt;suppressNotFoundWarnings(false);

Zend_Session::$_unitTestEnabled = true;
Zend_Session::start();

?&gt;
</pre>
<p>When this is done, let&#8217;s write first controller test case to see if that&#8217;s working properly.<br />
(In my current configuration, when I create new controller  in project using Zend tool integration,<br />
there is also new file created inside “tests/Application/Controllers” folder named “Original_controller_nameTest.php”).</p>
<p>If controllerTest is not created , we can always create it manually.</p>
<p>Create new php class document and save it inside  “tests/application/controllers/” folder and give it a name: “IndexControllerTest.php”.<br />
Enter code inside like this:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase {

    public function setUp() {
        $this-&gt;bootstrap = new Zend_Application(
                        'testing',
                        APPLICATION_PATH . '/configs/application.ini'
        );
        parent::setUp();
    }

    public function testHomePageIsASuccessfulRequest() {
        $this-&gt;dispatch('/index');
        $this-&gt;assertFalse($this-&gt;response
                        -&gt;isException());
        $this-&gt;assertNotRedirect();
    }

    public function tearDown() {
        /* Tear Down Routine */
    }

}
</pre>
<p>Now it&#8217;s time for testing: right click on the project name in projects explorer and choose “Test” or press Alt+F6 combination to run tests.</p>
<p>If everything is set up properly, then you will see test results in “test result” window.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/unit-testing-with-zend-framework-setting-up-environment-for-the-first-test-using-netbeans-ide-for-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to move existing WordPress site to another server</title>
		<link>http://inchoo.net/wordpress/how-to-move-existing-wordpress-site-to-another-server/</link>
		<comments>http://inchoo.net/wordpress/how-to-move-existing-wordpress-site-to-another-server/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 10:21:53 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[administration]]></category>
		<category><![CDATA[cms]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=8773</guid>
		<description><![CDATA[Some experienced developers would say: &#8220;Piece of cake , I can do it for about 15 minutes!&#8221; But, is it really so easy and trivial task? It&#8217;s not so heavy, but you have to pay attention on some really important &#8230;<p><a href="http://inchoo.net/wordpress/how-to-move-existing-wordpress-site-to-another-server/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>Some experienced developers would say: &#8220;Piece of cake , I can do it for about 15 minutes!&#8221;<br />
But, is it really so easy and trivial task?</p>
<p>It&#8217;s not so heavy, but you have to pay attention on some really important things and because of that,  I would like to say that it is not heavy but more sensitive task to do.</p>
<p>So, let&#8217;s start with article.</p>
<p><span id="more-8773"></span></p>
<p>Imagine this situation:<br />
We have one live site on <em>http://somedomainold.com</em> with fully functional WordPress installation, many articles, plugins installed on the site. Let&#8217;s say that current database is bigger than 500 Mb. We have access to control panel, ftp and also ssh on live server.<br />
Now we want now to copy same WordPress installation to<em> http://portal.somedomain.com</em> (into sub-domain of new domain on new server).</p>
<p>Why did I mentioned SSH?</p>
<p>Because I don&#8217;t want to download database file and then upload it again on new test server but I want to transfer whole data without downloading it.<br />
(Of course, in this case we must have ftp and ssh access to new server also).</p>
<p><em>TIP: For those that never used SSH before, I would advice that use Google for basic UNIX terminal commands, because they would need them. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </em></p>
<p>First of all, we have to back up live site (just in case something goes wrong) and also we can use backup to transfer both database backup and files backup to new server without problems.<br />
Often it could be done through control panel of live site. If not, there are alternatives, but I will talk just about  first mentioned case for now.</p>
<p>When backup of whole site is finished, copy that &#8216;somefile.tgz&#8217; backup file into public folder either from control panel or from some root ftp access so we could download that file via URL (for example: www.somedomainold.com/somefile.tgz.  (Do not forget to delete it after transferring!)<br />
Next, we have to connect by SSH to new server with our credentials (I often use Putty for SSH access because it is relatively simple, but there are more tools available for free).<br />
Fire up Putty and enter basic connection information in sessions category: Host-name / IP address of server we will connect to and press &#8216;Open&#8217; button to start the session.</p>
<p><img class="alignleft size-full wp-image-8777" title="moving_wp1" src="http://inchoo.net/wp-content/uploads/2011/03/moving_wp1.jpg" alt="" width="600" height="183" /></p>
<p><img class="alignleft size-full wp-image-8778" title="moving_wp2" src="http://inchoo.net/wp-content/uploads/2011/03/moving_wp2.jpg" alt="" width="600" height="87" /></p>
<p>If all went right you should see console like this:</p>
<p><img class="alignleft size-full wp-image-8779" title="moving_wp3" src="http://inchoo.net/wp-content/uploads/2011/03/moving_wp3.jpg" alt="" width="600" height="89" /></p>
<p>Now it&#8217;s time to do some UNIX stuff.<br />
First we want to choose our folder on server where we will host out new wordpress installation. (Using comands “cd”, “ls” will give us that possibility).<br />
Next, we need to is &#8216;download&#8217; that backup file from old server to new. We can do it with “wget” command in terminal.</p>
<p><img class="alignleft size-full wp-image-8780" title="moving_wp4" src="http://inchoo.net/wp-content/uploads/2011/03/moving_wp4.jpg" alt="" width="600" height="40" /></p>
<p>After that we want to decompress our downloaded backup package and move site files from inside unpacked folder to our sub-domain directory and also extract our sqldump file so we could restore it on our mysql database on new server. (I didn&#8217;t mention that we should first create mysql database and assign a database user with root credentials to it and one of the easiest possibilities is to do that through control panel of new site).<br />
For file decompressing you can use &#8216;tar -zxvf yourfile.tar.gz &#8216;.</p>
<p>Because I went too deep in details, let&#8217;s back to main theme.</p>
<p>After these &#8216;few&#8217; steps, we should ensure that all is on it&#8217;s place, so finally we should finish with folder structure like this:</p>
<p>/html/portal/<br />
here should be out wordpress installation (index.php, .htaccess, folders wp-content etc.)</p>
<p>(By the way, folder &#8216;html&#8217; is in our case root domain public directory and folder name portal is our sub-domain folder where http://portal.somedomain.com points to). Why is this important? Because of .htaccess setup later in this article.</p>
<p>Next we should replace all occurrences of &#8216;http://somedomainold.com&#8217; with &#8216;http://portal.somedomain.com&#8217; in our sqldump file.<br />
First time I tried to do that with &#8216;nano&#8217; text editor in SSH terminal, but database was too big for that editor, so Putty and SSH connection crashed every time and I decided to take advantage of another tool in terminal, so I used &#8216;vi&#8217; editor for that purpose because it won&#8217;t load whole file in memory, just visible part so terminal wouldn&#8217;t crash.<br />
(Use Google to search for &#8216;find and replace with vi&#8217; tutorial).</p>
<p>After replacing domain names in sql dump file save it and exit vi editor.</p>
<p>So, now we have files of site on right place and also sql dump file ready to restore to new database.<br />
(of course while &#8216;vi&#8217; editor is open we should probably add line on top of existing sql statements: USE new_database_name; )</p>
<p>Let&#8217;s Google again for instructions how to restore sql dump file to mysql using console. There are plenty of tutorials doing that.</p>
<p>When restoring database is completed we are almost ready to start our transferred wordpress site.</p>
<p>Open up your browser and try to enter to wp-admin:  http://portal.somedomain.com/wp-admin,<br />
log in with old site credentials and check general settings for updating URLs of the site. Also check permalinks settings and save it again.<br />
If new wordpress site is not working or displays only frontpage and not other pages in menu, probably is some problem with rewrite and / or permissions in .htaccess file. So in that case – delete .htaccess file or rename it via ftp and go to wp-admin &#8211; &gt; settings &#8211; &gt; permalinks again and save it again and new .htaccess file will be created  with some wordpress lines.<br />
From my experience because our installation was in root domain before and now is on subdomain,<br />
we need to add subdomain folder name before /index.php in .htaccess file (like on image) and all should be OK.</p>
<p><img class="alignleft size-full wp-image-8781" title="moving_wp5" src="http://inchoo.net/wp-content/uploads/2011/03/moving_wp5.jpg" alt="" width="600" height="354" /></p>
<p>Maybe there are easier ways to move site, maybe there are better ways, but I felt that I have to write about that from my experience before, so thank you for reading <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/wordpress/how-to-move-existing-wordpress-site-to-another-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Inchoo Developers module v1.0.1</title>
		<link>http://inchoo.net/ecommerce/magento/inchoo-developers-module-v101/</link>
		<comments>http://inchoo.net/ecommerce/magento/inchoo-developers-module-v101/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 11:48:46 +0000</pubDate>
		<dc:creator>Vedran Subotic</dc:creator>
				<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[module]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=6977</guid>
		<description><![CDATA[When you read the title of this article you will probably think that this module has all that you need for the development stage of your magento project. Once again, you are wrong. I was thinking of somenthing that can &#8230;<p><a href="http://inchoo.net/ecommerce/magento/inchoo-developers-module-v101/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>When you read the title of this article you will probably think that this module has all that you need for the development stage of your magento project. Once again, you are wrong.</p>
<p>I was thinking of somenthing that can be useful to me and speed up some common actions in development stage and I think that this module can be helpful, especially for those who works on &#8220;live&#8221; server and need to test some new features they have developed.</p>
<p><span id="more-6977"></span></p>
<p>Module is actually a switch between two admin controllers and you can use it quickly and easily by selecting action from dropdown menu &#8220;Production mode&#8221; and &#8220;Development mode&#8221;.<br />
<strong><br />
Magento development/production mode features:<br />
</strong> &#8211; Enables/disables Secret Key to URLs in admin area<br />
- Change admin startup page from Dashboard to System =&gt; Configuration (and vice versa)<br />
- Enables/disables charts in admin area<br />
- Merges on/off java script settings<br />
- Merges on/off css settings<br />
- Enables/disables demo store notification and replaces message with development mode message</p>
<p>Structure of the module:<br />
<a href="http://inchoo.net/wp-content/uploads/2010/12/module_structure.png"><img class="aligncenter size-full wp-image-6991" title="module_structure" src="http://inchoo.net/wp-content/uploads/2010/12/module_structure.png" alt="" width="620" height="632" /></a></p>
<p>As you can see from <strong>config.xml</strong> file,<br />
module also have features like <strong>custom admin theme, custom translation files and layout updates</strong>:</p>
<pre class="brush: php; title: ; notranslate">
&lt; ?xml version=&quot;1.0&quot;?&gt;
&lt;!--
/**
* Magento Commercial Edition
*
* @category	Inchoo
* @package		Inchoo_Developers
* @author		Vedran Subotic - vedran@inchoo.net
*/
--&gt;
&lt;config&gt;
&lt;modules&gt;
&lt;inchoo_developers&gt;
&lt;version&gt;1.0.1&lt;/version&gt;
&lt;/inchoo_developers&gt;
&lt;/modules&gt;
&lt;global&gt;

&lt;helpers&gt;
&lt;inchoo_developers&gt;
&lt;class&gt;Inchoo_Developers_Helper&lt;/class&gt;
&lt;/inchoo_developers&gt;
&lt;/helpers&gt;

&lt;blocks&gt;
&lt;inchoo_developers&gt;&lt;class&gt;Inchoo_Developers_Block&lt;/class&gt;&lt;/inchoo_developers&gt;
&lt;inchoo_developers_admin&gt;&lt;class&gt;Inchoo_Developers_Block_Adminhtml&lt;/class&gt;&lt;/inchoo_developers_admin&gt;
&lt;/blocks&gt;

&lt;!-- models&gt;

&lt;!-- events&gt;

&lt;!-- resources&gt;

&lt;/global&gt;

&lt;frontend&gt;

&lt;routers&gt;
&lt;inchoo_developers&gt;
&lt;use&gt;standard&lt;/use&gt;
&lt;args&gt;
&lt;module&gt;Inchoo_Developers&lt;/module&gt;
&lt;frontname&gt;inchoo_developers&lt;/frontname&gt;
&lt;/args&gt;
&lt;/inchoo_developers&gt;
&lt;/routers&gt;
&lt;translate&gt;
&lt;modules&gt;
&lt;inchoo_developers&gt;
&lt;files&gt;
&lt;default&gt;Inchoo_Developers.csv&lt;/default&gt;
&lt;/files&gt;
&lt;/inchoo_developers&gt;
&lt;/modules&gt;
&lt;/translate&gt;
&lt;layout&gt;
&lt;updates&gt;
&lt;inchoo_developers&gt;
&lt;file&gt;developers.xml&lt;/file&gt;
&lt;/inchoo_developers&gt;
&lt;/updates&gt;
&lt;/layout&gt;

&lt;/frontend&gt;

&lt;adminhtml&gt;
&lt;translate&gt;
&lt;modules&gt;
&lt;inchoo_developers&gt;
&lt;files&gt;
&lt;default&gt;Inchoo_Developers_Adminhtml.csv&lt;/default&gt;
&lt;/files&gt;
&lt;/inchoo_developers&gt;
&lt;/modules&gt;
&lt;/translate&gt;
&lt;menu&gt;
&lt;inchoo_developers translate=&quot;title&quot; module=&quot;inchoo_developers&quot;&gt;
&lt;title&gt;Inchoo Developers&lt;/title&gt;
&lt;sort_order&gt;0&lt;/sort_order&gt;
&lt;children&gt;
&lt;switch_development translate=&quot;title&quot; module=&quot;inchoo_developers&quot;&gt;
&lt;title&gt;Development Mode&lt;/title&gt;
&lt;action&gt;adminhtml/switch_development&lt;/action&gt;
&lt;sort_order&gt;100&lt;/sort_order&gt;
&lt;/switch_development&gt;
&lt;switch_production translate=&quot;title&quot; module=&quot;inchoo_developers&quot;&gt;
&lt;title&gt;Production Mode&lt;/title&gt;
&lt;sort_order&gt;200&lt;/sort_order&gt;
&lt;action&gt;adminhtml/switch_production&lt;/action&gt;
&lt;/switch_production&gt;
&lt;/children&gt;
&lt;/inchoo_developers&gt;
&lt;/menu&gt;
&lt;acl&gt;
&lt;resources&gt;
&lt;admin&gt;
&lt;children&gt;
&lt;inchoo_developers translate=&quot;title&quot; module=&quot;inchoo_developers&quot;&gt;
&lt;title&gt;Inchoo Developers&lt;/title&gt;
&lt;sort_order&gt;0&lt;/sort_order&gt;
&lt;children&gt;
&lt;switch_development translate=&quot;title&quot; module=&quot;inchoo_developers&quot;&gt;
&lt;title&gt;Development Mode&lt;/title&gt;
&lt;sort_order&gt;100&lt;/sort_order&gt;
&lt;/switch_development&gt;
&lt;switch_production translate=&quot;title&quot; module=&quot;inchoo_developers&quot;&gt;
&lt;title&gt;Production Mode&lt;/title&gt;
&lt;sort_order&gt;200&lt;/sort_order&gt;
&lt;/switch_production&gt;
&lt;/children&gt;
&lt;/inchoo_developers&gt;
&lt;/children&gt;
&lt;/admin&gt;
&lt;/resources&gt;
&lt;/acl&gt;
&lt;/adminhtml&gt;

&lt;admin&gt;
&lt;routers&gt;
&lt;adminhtml&gt;
&lt;args&gt;
&lt;modules&gt;
&lt;sintax before=&quot;Mage_Adminhtml&quot;&gt;Inchoo_Developers_Adminhtml&lt;/sintax&gt;
&lt;/modules&gt;
&lt;/args&gt;
&lt;/adminhtml&gt;
&lt;/routers&gt;
&lt;/admin&gt;

&lt;stores&gt;
&lt;admin&gt;
&lt;design&gt;
&lt;theme&gt;
&lt;default&gt;inchoo&lt;/default&gt;
&lt;/theme&gt;
&lt;/design&gt;
&lt;/admin&gt;
&lt;/stores&gt;

&lt;adminhtml&gt;
&lt;layout&gt;
&lt;updates&gt;
&lt;inchoo_developers&gt;
&lt;file&gt;developers.xml&lt;/file&gt;
&lt;/inchoo_developers&gt;
&lt;/updates&gt;
&lt;/layout&gt;
&lt;/adminhtml&gt;

&lt;/config&gt;
</pre>
<p>Next version of <strong>&#8220;Inchoo Developers&#8221;</strong> module will have implemented<br />
<strong>- cache management<br />
- log management<br />
</strong></p>
<p>Please give us some feedback what you can think of that would be great to implement in this module.<br />
Download <a href="http://inchoo.net/wp-content/uploads/2010/12/inchoo_developers_module.zip">Inchoo Developers module</a>.<br />
Thanks, Vedran.<br />
Enjoy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/inchoo-developers-module-v101/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Developing extensions that react unobtrusively with Magento</title>
		<link>http://inchoo.net/ecommerce/magento/developing-extensions-that-react-unobtrusively-with-magento/</link>
		<comments>http://inchoo.net/ecommerce/magento/developing-extensions-that-react-unobtrusively-with-magento/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 11:43:01 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[Extensions]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extension]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10038</guid>
		<description><![CDATA[The way I see it, there are two type of extensions for Magento (or even any other eCommerce solution): Community Free/Commercial extensions Custom extensions Community Free/Commercial extensions would be all those extensions that you can either freely download/install trough various &#8230;<p><a href="http://inchoo.net/ecommerce/magento/developing-extensions-that-react-unobtrusively-with-magento/">Read more</a><p>]]></description>
			<content:encoded><![CDATA[<p>The way I see it, there are two type of extensions for Magento (or even any other eCommerce solution):</p>
<ol>
<li>Community Free/Commercial extensions</li>
<li>Custom extensions</li>
</ol>
<p>Community Free/Commercial extensions would be all those extensions that you can either freely download/install trough various websites or official Magento connect or purchase from the developer if they are commercial.</p>
<p>Custom extensions are those which result from custom development work by some freelance developer or development team, specific to project. Usually they tend to be non-general, in terms of not usable on wider range of other Magento projects as they fulfil specific client shop need.<span id="more-10038"></span></p>
<p>If you ask me, there is a serious &#8220;issue&#8221; with a way how most of “(1) Community Free/Commercial extensions” extensions are developed. More precisely how they handle the view files in Magento. </p>
<p>Let me give you a simple example, a “Tweet this button”. Even an experienced frontend Magento developer will tell you that most likely he will just open the appropriate view file from theme and copy-paste the twitter button HTML/JS code into it. By “appropriate” we are referring to a view file which renders on a page position where we would like to see our twitter button. </p>
<p>To be a bit more precise in or example, let’s say we need to add this twitter button on the “Product view page”, right under the default “Be the first to review this product” text. Your average (or even experienced frontend developer) would most likely just open the “app/design/frontend/base/default/template/review/helper/summary.phtml” file and copy pasted twitter button code implementation at the very bottom of the file, save it and you are done.</p>
<p>Advanced frontend developer would most likely do one of the two things:</p>
<ol>
<li>Create a new view file somewhere in the theme folder, add the appropriate block entry into the layout xml file, then open the “app/design/frontend/base/default/template/review/helper/summary.phtml” and just add something like &#8220;echo $this->getChildHtml(&#8216;twitter_button&#8217;)&#8221;.</li>
<li>Create a static block inside the Magento admin, where he would copy pasted button code, then simply render the content of that static block in the “app/design/frontend/base/default/template/review/helper/summary.phtml” file.</li>
<li>Create extension that has it’s own block class, that is set to use special view file, that uses special entry on one of our layout files, that again uses &#8220;echo $this->getChildHtml(&#8216;twitter_button&#8217;)&#8221;.</li>
</ol>
<p>In my 2 years practice, solution (1) seems like most likely as you just want to get the job than, and you want to do it as fast as possible. And this is OK, if we are talking about environment where you are paid as a developer to implement design as this can be considered, design specific functionality, or custom developer/implemented specifically for this project so no need to do it as extension that will be redistributed later.</p>
<p>Now, there are certainly other approaches one can take besides these 3. However, out of these 3 I would say that the third one presents the biggest challenge since it talks about the “extension development”.</p>
<p>As a backend developer, I am most disappointed with the way how most extensions tend to use existing theme/view/block files to “dump” their content. For the 3rd example above, your twitter extension, no matter how cool, uses “app/design/frontend/base/default/template/review/helper/summary.phtml” file. Even doe this use is minimal, in terms of just one extra line that says &#8220;echo $this->getChildHtml(&#8216;twitter_button&#8217;)&#8221; it is still an issue.</p>
<p>Why is it an issue? It’s just one file? Well, what happens if John Doe writes another cool Magento extension that adds “Google Buzz” on the same place. And the author of that extension decided to use the same “app/design/frontend/base/default/template/review/helper/summary.phtml” file to output its content. Even if his usage is minimal, you now have 2 extensions that use the same view file, summary.phtml. Basically, you now have an issue.</p>
<p>This issue is specially expressed with the “color switcher”, “photo zoom”, or similar type extensions that poke around “Product View Page” trying to add all sort of fancy effects or functionality. And most of them do that by usig “product.view” or “media.phtml” file. So, if you are not careful you can easily screw up your store with installing 2-3 “similar” extensions as they might use same files which then overwrite each other functionality as you install them.</p>
<p>Ok, I see the issue, now what? Well, not sure what “great” advice to give you. I would say that for extension developers it all comes down to few simple questions: </p>
<ol>
<li>How destructive you want to be with your extension?</li>
<li>What happens when I remove it (any sql issues, any layout issues, any view file issues)?</li>
<li>What happens if someone else installs the “similar” extension?</li>
<li>What happens when I do “&#8221;System > Configuration > Advanced > Advanced > Disable Modules Output&#8221; =>Disable”?</li>
<li>What happens and how will you handle the scenario where others want to “interact” with your extension (do you dispatch any events)?</li>
</ol>
<p>Sadly, at the moment (referring to today&#8217;s date 26/11/2010), high number of Magento extension I saw (even some pretty expensive) fail on these questions (saying this figuratively of course, not that I actually interviewed the developers).</p>
<p>What can we do then do code Magento extensions more unobtrusively? Well, you can start by studying the event/observers system. When it comes to Magento there all lot of options you can try out. Images below show what you can do by “observing” the “core_block_abstract_to_html_after” event. </p>
<p><a href="http://activecodeline.net/wp-content/uploads/2010/11/unobtrusively1.png">click to see img1</a>, <a href="http://activecodeline.net/wp-content/uploads/2010/11/unobtrusively2.png">click to see img2</a>, <a href="http://activecodeline.net/wp-content/uploads/2010/11/unobtrusively3.png">click to see img3</a>, <a href="http://activecodeline.net/wp-content/uploads/2010/11/unobtrusively4.png">click to see img4</a>, <a href="http://activecodeline.net/wp-content/uploads/2010/11/unobtrusively5.png">click to see img5</a></p>
<p>Surely there are lot of sideby quastions one might have applying approach like this. Questions like, how does this relate to block caching functionality, etc. I will leave answers to you, as I simply wanted to get you thinking.</p>
<p>Looking forward to your feedback.</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/developing-extensions-that-react-unobtrusively-with-magento/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

