<?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>MV Associati Tech Gems &#187; zend framework 2</title>
	<atom:link href="http://www.mvassociati.it/en/gems/topic/zend-framework-2/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mvassociati.it/en/gems</link>
	<description>Technical Article from MV Associati experience</description>
	<lastBuildDate>Fri, 04 Aug 2017 10:31:17 +0000</lastBuildDate>
	<language>en-EN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Zend Framework 2 Routing Basics</title>
		<link>http://www.mvassociati.it/en/gems/php/zf2-routing-basics?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=zend-framework-2-routing-basics</link>
		<comments>http://www.mvassociati.it/en/gems/php/zf2-routing-basics#comments</comments>
		<pubDate>Tue, 04 Jun 2013 13:47:45 +0000</pubDate>
		<dc:creator>drigani</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[routes]]></category>
		<category><![CDATA[routing]]></category>
		<category><![CDATA[zend framework 2]]></category>
		<category><![CDATA[zf2]]></category>

		<guid isPermaLink="false">http://www.mvassociati.it/en/gems/?p=607</guid>
		<description><![CDATA[Earlier this year, I&#8217;ve had the opportunity to speak at the Italian Zfday in Milan, as well as at the Unconf of the PHPDay, the Italian conference on PHP, which is held every year in Verona. In both occasions, I introduced Zend Framework 2 Routing in a talk titled: “Full sail: easy routing with the [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this year, I&#8217;ve had the opportunity to speak at the Italian <a title="Zend Framework Day" href="http://www.zfday.it/">Zfday</a> in Milan, as well as at the Unconf of the <a title="PHPDay" href="http://2013.phpday.it/">PHPDay</a>, the Italian conference on PHP, which is held every year in Verona. In both occasions, I introduced Zend Framework 2 Routing in a talk titled: “Full sail: easy routing with the ZF2” (original title: &#8220;<a title="Zend Framework Routing Slides on Slideshare" href="http://www.slideshare.net/drigani/levate-lancora-rotte-senza-problemi-con-zf2">Levate l&#8217;ancora: Rotte senza problemi con ZF2</a>&#8220;). These conferences turned out to be interesting experiences, allowing me to get in touch with the Italian Zend Framework Community. From the positive feedback I have received, I&#8217;ve decided to write some blog posts about the topics that were introduced in my talks. So, here it comes this post, the first of a series about zf2 routing.<span id="more-607"></span></p>
<h2>For starters, what is routing?</h2>
<p>The fundamental principle of routing is to <strong>match incoming requests </strong>reaching an application and <strong>decide</strong> which fragment of<strong> code to execute</strong>. That could mean matching either an http request or a console requests (if you are interacting with a Command Line Interface application), and extracting the parameters that determine which snippet of code (IE which controller and then which action) to execute. The other basic principle is to <strong>assemble</strong> URLs and commands back. That is, from a set of parameters, to build the path of the route. In terms of an example, this means coming up with the /products/view/some_product URL starting from the controller = products, action = view, slug = some_product parameters*.</p>
<p>*I am aware this might not be the best possible example URL, but I hope it gets the message across in simple terms.</p>
<h2>Why should we care about routing?</h2>
<p>There are different reasons why routing is important. The simplest and most important one is that without routing your application won&#8217;t work   Even in a working application, though, properly handling routing is important. That&#8217;s for different reasons, which can be summarized as follows:</p>
<p>- good URLs are easier to remember, type and share through word of mouth<br />
- they also make it easier for search engines to properly index websites and web applications<br />
- they allow for clean RESTful interfaces to be build<br />
- they improve web application security, because they make it easier for parameters to be properly handled</p>
<h2></h2>
<p><a href="http://www.mvassociati.it/en/gems/php/zf2-routing-basics/attachment/pirate-smoking-a-cigar" rel="attachment wp-att-611"></a></p>
<p>&nbsp;</p>
<h2>Routing within the Zend Framework 2</h2>
<h3>Under the Hood</h3>
<p>The basic unit of routing is a so called route, which is nothing but a PHP class implementing the following interface:</p><pre class="crayon-plain-tag">namespace Zend\Mvc\Router;

use zend\Stdlib\RequestInterface as Request;

interface RouteInterface
{
  public static function factory(array $options = array());
  public function match(Request $request);
  public function assemble(array $params = array(), array $options = array());
}</pre><p>The RouteInterface includes the  static method <strong>factory</strong>, which is used to create new routes. Every route is constructed with arguments (usually fetched from specific project/module configuration file). The <strong>match</strong> method, in turn, accepts a new Request, and determines if the request matches current route. If true, it then returns a RouteMatch object, which is a container object, that includes the route name and most likely all route parameters and values. Last, we also have the <strong>assemble</strong> method, which takes options and parameters and builds the path of a route (usually an URL).</p>
<p>We will rarely need to worry about implementation details of these methods, though, because the framework will take care of passing the configuration and creating our routes according to our definitions in each module configuration directives (as we&#8217;ll shortly see).</p>
<h3>Defining new routes</h3>
<p>Routes for each module shall be defined within the module configuration file, which can be found in every module&#8217;s root folder. The default Zend Framework Skeleton app also has its own Module.php file in <strong><em>/config/modules.config.php:</em></strong></p>
<p><a href="http://www.mvassociati.it/en/gems/php/zf2-routing-basics/attachment/modulepic-2" rel="attachment wp-att-608"></a></p>
<p>&nbsp;</p>
<p>The section dealing with routing is the one which goes under the <strong>router</strong> key; <strong>routes</strong> contains a list of our routes in array form:</p><pre class="crayon-plain-tag">return array(
  'router' =&gt; array(
    'routes' =&gt; array(
      'contact' =&gt; array(
        'type' =&gt; 'Literal',
        'options' =&gt; array(
          'route' &nbsp;&nbsp;&nbsp;=&gt; '/contact',
          'defaults' =&gt; array(
            'controller' =&gt; 'Application\Controller\Contact',
            'action' &nbsp;&nbsp;&nbsp;&nbsp;=&gt; 'index',
          ),
        ),
      ),
    ),
  ),
),</pre><p>In the basic example above, we defined a route named “contact”, of type Literal (all different Route types will be covered in a forthcoming post). Basically we just told the framework to dispatch users requesting the ‘/contact’ URL to the Contact controller, and to have the IndexAction method to be executed.</p>
<h3>What about route stacks</h3>
<p>The ZF2 router is a collection of routes, based on a priority stack. As it was happening in Zend Framework 1, routes can be added to a route list; the last added route is the one tested first. The same now happens in ZF2; we can now also take advantage of the new <strong>priority</strong> attribute, though. This means that every route will have a priority value, and highest priorty route will be tested first. I&#8217;m sure this will make it easier to keep things organized without needing to worry much about route position within configuration files. This will also make it easier for custom configurations to be used to override third party default configurations.</p>
<p>Every router (there are different types, which we&#8217;ll take a look at shortly) implements this interface:</p><pre class="crayon-plain-tag">namespace Zend\Mvc\Router;

interface RouteStackInterface extends RouteInterface
{
  public function addRoute($name, $route, $priority = null);
  public function addRoutes(array $routes);
  public function removeRoute($name);
  public function setRoutes(array $routes);
}</pre><p>All methods are self-explanatory, so I won&#8217;t go in further detail here. This is with the exception of the <strong>setRoutes</strong> method, which probably deserves some explanation. This method in fact replaces current routes in the stack with the new ones provided as an argument. So, it first removes current routes, then adding the new ones.</p>
<h3>Router types</h3>
<p>There are different implementations of the aforementioned Router base class:</p>
<ul>
<li><strong>SimpleRouteStack:</strong> the most basic implementation, which we can use and extend to make our own router stack class.</li>
<li><strong>Http\TreeRouteStack</strong>: the most common kind of router, it is used to create a tree of routes to deal with http requests, using a B-tree algorithm to match routes (this ensures that evaluation is efficiently made, as we&#8217;ll shortly see).</li>
<li><strong>Console\SimpleRouteStack</strong>: used in the realm of CLI applications and use to take care of command line arguments. This kind of router will be processed when our application is run from a console terminal window.</li>
</ul>
<h3></h3>
<h3>Tree Routing</h3>
<p>Zend Framework 2 introduces the Tree Routing concept as a big innovation. In fact, it&#8217;s very easy to use and its <strong>performance</strong> is great also: it&#8217;s much faster than its ZF1 counterpart. This is for multiple reasons: first off is the fact that the framework doesn&#8217;t try to match incoming requests with every single route anymore. This happens because every route can now have an unlimited number of <strong>children routes</strong>, which aren&#8217;t evaluated if parent route didn&#8217;t match the request first. Children routes are in fact only instantiated when the router matches or assembles their respective parent routes.</p>
<p>A Tree Route will consist of the following configuration:</p>
<ul>
<li>A <strong>base route</strong>, known as root route, which describes the base path (first part of an URL, for example);</li>
<li>The <strong>may_terminate</strong> key, which is set to false by default, telling the router whether the route may terminate or not.</li>
<li>The <strong>child_routes</strong> key, an array containing additional routes that stem from the base “route”. Each child route can itself be a Tree Route</li>
</ul>
<p>Example:</p><pre class="crayon-plain-tag">return array(
  'router' =&gt; array(
    'routes' =&gt; array(
      'zf' =&gt; array(
      'type' =&gt; 'Literal',
      'options' =&gt; array(
        'route' =&gt; '/zf',
        'defaults' =&gt; array(
        '__NAMESPACE__' =&gt; 'Application\Controller',
        'controller' &nbsp;&nbsp;&nbsp;=&gt; 'Article',
        'action' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&gt; 'index',
      ),
    ),
    'may_terminate' =&gt; true,
    'child_routes' =&gt; array(
    'default' =&gt; array(
      'type' &nbsp;&nbsp;&nbsp;=&gt; 'Segment',
      'options' =&gt; array(
        'route' &nbsp;&nbsp;&nbsp;=&gt; '/:action',
        'constraints' =&gt; array(
          'action' &nbsp;&nbsp;&nbsp;&nbsp;=&gt; '[a-zA-Z][a-zA-Z0-9_-]*',
        ),
      ),
    ),
  ),</pre><p></p>
<h2>Summary</h2>
<p>In this first post about the Zend Framework 2 routing, I&#8217;ve introduced what&#8217;s a route, what&#8217;s routing, how the routing system works in the Zend Framework 2, and how it differs (especially from a performance point of view) from the ZF1 implementation. In my next post, I will be covering different HTTP route types we have at hand. Is there anything else you&#8217;d like to know? Just let me know with a comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mvassociati.it/en/gems/php/zf2-routing-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asset management in Zend Framework 2</title>
		<link>http://www.mvassociati.it/en/gems/php/asset-management-zend-framework-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=asset-management-in-zend-framework-2</link>
		<comments>http://www.mvassociati.it/en/gems/php/asset-management-zend-framework-2#comments</comments>
		<pubDate>Fri, 08 Mar 2013 10:47:42 +0000</pubDate>
		<dc:creator>stefanovalle</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[assetmanager]]></category>
		<category><![CDATA[assets]]></category>
		<category><![CDATA[modules]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework 2]]></category>
		<category><![CDATA[zf2]]></category>

		<guid isPermaLink="false">http://www.mvassociati.it/en/gems/?p=554</guid>
		<description><![CDATA[During the last February I’ve had the chance to be a speaker at Zend Framework Day in Italy where I made a talk about zf2 modules. I think the topics covered deserve more time and space, so this blog post is the first of a series about how to take advantage of new ZF2 modular [...]]]></description>
			<content:encoded><![CDATA[<p>During the last February I’ve had the chance to be a speaker at Zend Framework Day in Italy where I made a talk about zf2 modules. I think the topics covered deserve more time and space, so this blog post is the first of a series about how to take advantage of new ZF2 modular structure.<br />
One of the first issues a developer runs into when dealing with ZF2 modules is how to <strong>arrange assets between modules</strong>. A Web asset is simply any css file, js library, image (and generally all static files) a module needs to work properly.<br />
<span id="more-554"></span></p>
<p></p>
<h3>The problem: where assets should be placed?</h3>
<p>The first problem to solve is: where my module’s assets should be placed to let me (the developer) forget about them? Because I should not care about assets provisioning, I would spend my time working on module itself! To simplify the problem, let me break it into two (not so) different use cases.</p>
<h4>Shared assets</h4>
<p>A module probably has many shared assets with other modules: javascript libraries, images, css files, etc. A common practice is to place all of them inside the project /public folder. Despite this is the simplest solution, it’s not the best. Copy/paste manually is never a good practice, besides copying all files inside the same folder will contribute to lose the explicit dependencies the module has with its assets.</p>
<h4>Single module’s assets</h4>
<p>In many cases a module has also some assets being used only by itself. We know that a module should focus on a single project functionality, so it should contain all the things that functionality needs to work well. The simplest answer now is probably the best: we should place all assets inside the module.</p>
<h3>Some naive solutions</h3>
<p><strong>How should we make the web server aware that out modules have some assets that need to be visible inside our view scripts?</strong></p>
<p>We could copy all assets (also those needed by a single module) inside public folder, every time one of them is added or updated. This is a bad practice, trust me!</p>
<p>We could use symlinks to let files be viewed inside another folder. Or we could do some apache htaccess tuning to let web server search files through all module folders. Luckily, there is a better way to handle things…</p>
<h3>Welcome AssetManager module</h3>
<p>AssetManager is a ZF2 module (<a href="https://github.com/RWOverdijk/AssetManager">https://github.com/RWOverdijk/AssetManager</a>) aimed at managing assets, that resolve exactly our problem. It’s based on the Assetic asset management framework for PHP (<a href="https://github.com/kriswallsmith/assetic">https://github.com/kriswallsmith/assetic</a>).</p>
<p>I don’t cover module provisioning and installation phases here because online there are straightforward and well organized articles about this (take a look on module’s wiki: <a href="https://github.com/RWOverdijk/AssetManager/wiki">https://github.com/RWOverdijk/AssetManager/wiki</a>).</p>
<p>Instead, here I would like to explain how this module can be a real time (and headache) saver for all ZF2 developers.</p>
<p>After completing the install process, the module can take care of your assets through two simple steps:</p>
<ol>
<li><strong>Create a folder where assets should be placed.</strong> I typically suggest to use the /assets folder inside your module. Obviously you’re free to use whatever name you prefer. Sometimes you find assets inside a folder named /public, but this could be confused with the folder where the web server points to. So I suggest to choose a different name to make things clear. Use the folder you prefer, but keep in mind the rule of thumb: use always the same location inside all your modules, to make them more clear and readable.</li>
<li><strong>Add</strong> the following <strong>rule to your module’s configuration file</strong> (/config/module.config.php – “assets” refers to the folder where your assets are placed):</li>
</ol>
<p></p><pre class="crayon-plain-tag">'asset_manager' =&gt; array(
    'resolver_configs' =&gt; array(
&nbsp;&nbsp;&nbsp;&nbsp;    'paths' =&gt; array(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    __DIR__ . '/../assets',
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;),
&nbsp;&nbsp;&nbsp; ),
),</pre><p>With this two simple steps we are telling the AssetManager where the assets of our module are placed.</p>
<p><strong>That’s it!</strong> Now when an asset is not found inside project /public folder, the AssetManager module’ll look inside our module /assets folder to find the requested file. From now you could link assets inside your views simply as follows:</p><pre class="crayon-plain-tag">&lt;?php &nbsp;echo $this-&gt;headLink()-&gt;prependStylesheet($this-&gt;basePath() .&nbsp;
                                                '/css/aCssFile.css');&nbsp;?&gt;</pre><p>&nbsp;</p>
<p>In this way, <strong>we don’t need to worry about where our css is physically located</strong>, just link it as if it was placed inside /public folder. So simple and so amazing! In this way you can <strong>place all module assets (both shared and exclusive) inside the module. So that module is now really reusable</strong> inside other projects, without hidden dependencies.</p>
<p>Pay only attention to avoid colliding file rules. It’s not uncommon to have modules containing files with the same name. In this case prefixing the asset path with the module’s name (or slug) could solve the issue (this can be done through the ‘map’ key inside configuration file; take a look on the code in the following paragraphs for an example).</p>
<p>This is the simplest use of AssetManager we could make, but<strong> this module has many more features that are worth an extra look</strong>. Let me define some terms the module uses (each of this maps to a key of module’s config file):</p>
<ul>
<li><strong>Resolvers</strong> (resolver_configs key) allow to define where assets should be searched and how they are named / arranged. Many resolver types are available: MapResolver, CollectionResolver, PrioritizedPathsResolver and PathStackResolver (detailed infos and examples available here: <a href="https://github.com/RWOverdijk/AssetManager/wiki/Resolvers">https://github.com/RWOverdijk/AssetManager/wiki/Resolvers</a>)</li>
<li><strong>Filters</strong> (filters key) allow make some processing on assets before serving them (eg. Minify minification, compiling of css files)</li>
<li><strong>Cache</strong> (caching key), as the name suggest, allows to choose which caching policy use to speed up assets serving time</li>
</ul>
<h3>An example</h3>
<p>It’s a common practice to merge css files in order to limit the number of http requests (improving page serving speed). The AssetModule could help us to merge files automatically. Supposing our module has two css files (main.css and custom1.css), we could merge them together simply updating module’s config file as follows:</p><pre class="crayon-plain-tag">'asset_manager' =&gt; array(
    'resolver_configs' =&gt; array(
        'map' =&gt; array(
            'css/main.css' =&gt; __DIR__ . '/../assets/css/main.css',
            'css/custom1.css' =&gt; __DIR__ . '/../assets/css/custom1.css',
        ),
        'collections' =&gt; array(
            'css/merge.css' =&gt; array(
                'css/main.css',
                'css/custom1.css',
            ),
        ),
    ),
),</pre><p>&nbsp;</p>
<p>And the resulting view script is:</p><pre class="crayon-plain-tag">&lt;?php echo $this-&gt;headLink()-&gt;prependStylesheet($this-&gt;basePath() . 
                                                '/css/merge.css'); ?&gt;</pre><p>More code samples can be found on official module wiki (<a href="https://github.com/RWOverdijk/AssetManager/wiki">https://github.com/RWOverdijk/AssetManager/wiki</a>), that’s really well written and full of useful examples.</p>
<h3>Conclusion</h3>
<p>There are other ZF2 modules that provide asset management features. I personally like AssetManager because it’s really effective and simple to use. However is not important which module you decide to use, the important thing is that you should stop right now to manage assets manually. It’s a real boring and time wasting task, especially in the long run.</p>
<p>So now you’ve no excuses, <strong>this module requires no more than a few minutes to be installed and configured</strong>. Go and give it a try! And… after having configured your assets, don’t forget to <strong>enable AssetModule’s cache</strong>. That’s really a must to offer decent website performance and hence a good user experience.</p>
<p>For those who prefer a <strong>talk-like explanation</strong>, the extract of my Zend Framework Day presentation about this topic can be found <a href="http://www.slideshare.net/stefanovalle/zf2-asset-management">here</a>.</p>
<p>Image credit: http://www.flickr.com/photos/tracyleephoto/8322509672</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mvassociati.it/en/gems/php/asset-management-zend-framework-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
