<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
  <channel>
    <title>DASPRiD's Blog</title>
    <description>Latest posts about recent development topics</description>
    <pubDate>Fri, 19 Aug 2022 15:37:27 +0000</pubDate>
    <generator>Zend_Feed_Writer 2 (http://framework.zend.com)</generator>
    <link>https://dasprids.de/blog/</link>
    <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
    <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
    <atom:link rel="self" type="application/rss+xml" href="https://dasprids.de/blog/feed.xml"/>
    <item>
      <title>The long way to a new website</title>
      <description><![CDATA[After a long time, I managed to put up a completely overhauled website.]]></description>
      <pubDate>Tue, 03 May 2016 20:44:59 +0000</pubDate>
      <link>https://dasprids.de/blog/2016/05/03/the-long-way-to-a-new-website/</link>
      <guid>https://dasprids.de/blog/2016/05/03/the-long-way-to-a-new-website/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>It took me practically forever, but after a long time I managed to get a new website up and running. I had multiple new design ideas over the past few years, and even had a quite complex design for a business version of my website done by <a href="http://www.martes.de">MARTES NEW MEDIA</a>, but eventually I decided that I would not need a business website at all. About a week ago I started tinkering with the website agian, and decided to work one something new.</p>
<p>I heard about static site generators a while back already, but never came around to look more into them. So I started with a recommendation from <a href="http://ocramius.github.io/">Ocramius</a>, namely what he uses as well, <a href="https://sculpin.io/">Sculpin</a>. At first it seemed to work quite well, and I started to write up a nice layout with Bootstrap 3 and CSS. After that, I tried to set up all the different templates I would need, but quickly ran into a lot of bugs, some of which I could solve with workarounds, but others which were real showstoppers.</p>
<p>So I looked around on the web a little, and found out about a few more popular static site generators, the major ones being <a href="https://jekyllrb.com/">Jekyll</a>, <a href="https://gohugo.io/">Hugo</a> and <a href="http://blog.getpelican.com/">Pelican</a>. Well, I tried working with all of them and a few others, but eventually I always ran into one bug or another which made me really hate each one. Of course I asked Google a lot for workarounds and solutions, but all of those generators have a maintenance which makes most serious developers cry.</p>
<p>Eventually I gave up on that and concluded that if I want something working from A to Z, I'd have to write it myself. So I started writing a really small 200-line script, which generated my blog and the few static pages really nicely (and without bugs!). Since I'm a perfectionist though, I decided to write the entire thing down in a nice library, which I could eventually re-use if I'd want to. The code of the site generator is public, although it's currently combined with the <a href="https://github.com/DASPRiD/dasprids.de">repository of my website on GitHub</a>. You are allowed to fork it though if you like to use it for your own website. If interest would be large enough, I may even consider making the site generator its own composer package. </p>
<p>As I didn't want the website to be completely static, I also added <a href="https://disqus.com">Disqus</a> as a commenting platform. It was a little tricky to get my comments exported from my old system (let alone the articles, which I had to convert to markdown and then clean up manually), but I managed to link everything up properly.</p>
<p>Another change I decided was to finally have my website ran completely through HTTPS. I already had a few other domains of mine  set-up for that through <a href="https://letsencrypt.org/">Let's Encrypt</a>, but my old website had some hard-coded parts which made it impossible to run on HTTPS.</p>
<p>Last but not least, don't consider this the final version of the new website. I only wanted to bring it up so that no new comments get added to the old comment system. I will eventually add a few more static pages with more information about myself. But then, most of your are probably just interested in development topics, of which I may post more frequently in the foreseeable future.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Private communication between PHP classes</title>
      <description><![CDATA[How to protect commnication between your internal PHP classes.]]></description>
      <pubDate>Sun, 13 Dec 2015 17:08:59 +0000</pubDate>
      <link>https://dasprids.de/blog/2015/12/13/private-communication-between-php-classes/</link>
      <guid>https://dasprids.de/blog/2015/12/13/private-communication-between-php-classes/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<h1>Introduction</h1>
<p>I am currently working on <a href="https://github.com/Bacon/BaconPdf">BaconPdf</a>, and while doing so, I ran into an interesting problem. Consider that there are two classes, namely Document and Page. The user may extend both classes to add specific functionality, but they may never alter the underlying data structure, as that would mean that we'd always have to validate it completely whenever a Page is added to the Document. Thus we must prevent the user from ever getting access to that data structure.</p>
<h1>Implementation</h1>
<p>Since we don't have friend classes or private classes in PHP, this is kinda tricky. You cannot let the Document ask the Page for the data structure, as the user could do the same then. You also cannot let the Page tell the Document directly about it, as the user could tell the Document any invalid data structure then as well. Thus we need some kind of verification process, which doesn't involve validating the entire data structure. Thus I came up with the following architecture, which is somewhat related to the visitor design pattern. Consider the following Document class:</p>
<pre><code class="language-php">class Document
{
    private $pagesData = [];

    final public function addPage(Page $page)
    {
        $page-&gt;acceptDocument($this);
    }

    final public function addPageData(Page $page, $pageData)
    {
        if (!$page-&gt;verifyPageData($pageData)) {
            throw new DomainException('Supplied data are not coming from a Page');
        }

        $this-&gt;pagesData[] = $pageData;
    }
}</code></pre>
<p>This is pretty simple and explained just as quickly. There is a public function specifically designed for users, where they can simply call <code>addPage()</code> with their <code>Page</code> object and that's all they have to care about. Now there's an additional public method called <code>addPageData()</code> which will accept page data, but only together with a <code>Page</code> object. The document will ask the given page to verify the data it received and throw a DomainException if the verification fails.</p>
<p>Since the <code>$pagesData</code> property is private, even an extending class will not be able to read it or write to it. The <code>addPageData()</code> method has to be final though, as the user could otherwise intercept the <code>$pageData</code> in an extending class. The <code>addPage()</code> method has to be final as well, the reason for that is explained later. Now lets take a look at the <code>Page</code> class:</p>
<pre><code class="language-php">class Page
{
    private $pageData;

    public function __construct()
    {
        $this-&gt;pageData = new stdClass();
    }

    final public function acceptDocument(Document $document)
    {
        $document-&gt;addPageData($this, $this-&gt;pageData);
    }

    final public function verifyPageData(stdClass $pageData)
    {
        return $pageData === $this-&gt;pageData;
    }
}</code></pre>
<p>Here we have to methods again, of which none are actually meant for the user to be called. But even when they do call them, they can do no harm to the underlying data or even access it. Now when the user calls <code>addPage()</code> on the Document, it will pass itself to <code>acceptDocument()</code> on the <code>Page</code> object. This page object will tell the document to add its private <code>$pageData</code>, together with itself as an instance for verifying the data. The document will then call the <code>verifyPageData()</code> method on the <code>Page</code> object to make sure that the page data actually originate from that <code>Page</code> object.</p>
<p>Since the page data are an object, all we really have to do to verify them is to check that they reference the same object. The <code>verifyPageData()</code> method has to be final of course, as otherwise the user could extend the class and override the method to always return true. The <code>acceptDocument()</code> method does need to be final, as a user could override it and make it do nothing, which would break the entire workflow.</p>
<p>So, to come back to the earlier question, why the <code>addPage()</code> method on the document has to be final. The user could not only add pages to the document via the <code>addPage()</code> method, but also by calling <code>acceptDocument()</code> on the <code>Page</code> object. Thus, if a user would override the <code>addPage()</code> method to add additional functionality, it would be circumvented by adding the page via the <code>acceptDocument()</code> method. That's why there must not be any additional functionality in the <code>addPage()</code> method, it actually only exists for convenience there and to make the usage a bit more logical.</p>
<h1>Conclusion</h1>
<p>The entire approach is of course a lot of logic, and while it exposes three public functions which are technically not meant for the user, they cannot do any harm to the underlying structure by getting their hands on it. As this is PHP, they can still use reflection or abuse bound closures, but I'd consider that cheating. The important part is, that you cannot break the architecture via the public interface. It stil has the downside though that you do have a public interface, to which a change would be a backward incompatibility break, which must not be done in minor versions of a software, if you follow semver.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>A short status update about Zend Framework 3</title>
      <description><![CDATA[Beware, a lot of things will change with Zend Framework 3.]]></description>
      <pubDate>Mon, 31 Mar 2014 22:00:00 +0000</pubDate>
      <link>https://dasprids.de/blog/2014/04/01/a-short-status-update-about-zend-framework-3/</link>
      <guid>https://dasprids.de/blog/2014/04/01/a-short-status-update-about-zend-framework-3/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>As many of you surely know, the development of the next major version of Zend Framework pretty much came to a hold as the Zend team was and is still occupied with <a href="http://www.apigility.org/">apigility</a>. The maintenance of Zend Framework 2 is also coming along pretty slowly right now, although it's not completely stalled.</p>
<p>For those following the discussions in our development IRC channel more frequently, you probably saw that some of us are actually working on refactoring many components for Zend Framework 3, some a little more (like the completely rewritten <a href="https://github.com/DASPRiD/Dash">Dash Router</a>), and some with just minor BC breaks like the service manager, the event manager and everything around forms.</p>
<p>There was quite a bit of discussions on IRC, the mailing list and on GitHub about how we could speed up the development of ZF3, so we could get a release out in a proper time. We not only came to a final decision, but also developed a plan to reduce the number of future BC breaks permanently. So what does this look like? Well, this is actully a plan with multiple steps.</p>
<p>First we are going to define all component layers via interfaces within Zend Framework itself. We won't ship any concrete implementations with it, but only make our MVC layer consume and work with those interfaces. The next step is developing reference implementations as separate projects, although still maintained by Zend. This way we are still able to ship a complete application framework, while making it easier to completely swap out specific components. The reference implementations will hook into the system as normal modules, so that they can also supply application configuration on their own.</p>
<p>So what is the timeframe for all this you may ask? As I wrote earlier, we don't want to fall behind too much, so we planned to finalize all the interfaces until the end of this month. We then will write bridges to older ZF2 components where required, so that they can already be used in the new architecture. In cases where we already have new implementations in place, like the router, service mager and such, we will alter those to follow the defined interfaces.</p>
<p>Another plus side on this new approach is that we can directly target PHP 5.5 on components here it makes sense to use new features, while other components can still be PHP 5.4. For those components which make use of PHP 5.5 features, we will parallely maintain PHP 5.4 compliant versions, which will automatically be selected by composer if the user is running an older PHP version.</p>
<p>If everything goes as planned, we should have a beta release of Zend Framework 3 out by May 16th, and a release candidate around June 1st. Proposals for all interfaces will be posted throughout this month, so make sure to watch the mailing list and join the discussion and bring in your ideas!</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>About {@inheritDoc} and other useless documentation</title>
      <description><![CDATA[Why I don't like the redundant usage of {@inheritDoc} and pointless return type documentation like void.]]></description>
      <pubDate>Mon, 28 Oct 2013 00:33:52 +0000</pubDate>
      <link>https://dasprids.de/blog/2013/10/28/about-inheritdoc-and-other-useless-documentation/</link>
      <guid>https://dasprids.de/blog/2013/10/28/about-inheritdoc-and-other-useless-documentation/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>I've seen and followed many different documentation rules in my life. Everytime when I was taught something new for code documentation and it made any sense to me, I tend to addopt these pretty quickly. When looking back, some of the rules certainly made sense, especially when our poor IDEs weren't as good with resolving documentation as they are now. What I want to teach you with this article is, how to reduce redundant documentation and keep it as short as possible, without loosing any documentation from auto completion or API docs.</p>
<p>First, let's talk about the @return annotation. It became pretty popular in PHP to write &quot;@return void&quot; when the method will not return anything. Techncially though, it is actually returning &quot;null&quot;. But writing &quot;@return null&quot; isn't actually helping much either. Since you are really not returning anything, it is perfectly fine to ommit the @return annotation completely. Any IDE or API-doc generator will interpret this as the classical &quot;@return void&quot;.</p>
<p>So, let us start with a very simple interface to demonstrate all following usecases:</p>
<pre><code class="language-php">interface ToasterInterface
{
    /**
     * Toast a bread.
     *
     * This method will toast a bread for a given amount of seconds.
     *
     * @param Bread $bread
     * @param int   $time
     */
    public function toast(Bread $bread, $time);
}</code></pre>
<p>When generating API-docs from this with phpDocumentor, it will look like this:</p>
<pre><code>Toast a bread.

This method will toast a bread for a given amount of seconds.

    access: public

void toast (Bread $bread, int $time)

    Bread $bread
    int $time</code></pre>
<p>There's nothing really special about this you haven't seen before. Now there are quite a few ways people take to document the method in an implementation. I won't list all here to keep the article short, so let's just get to the point. If your method doesn't do anything special over the already documented interface, just leave the doc-block out. Every API-doc generator will take everything from the parent, which is in this case the short description, long description and all annotations. Now let's say that you want to change something, e.g. you throw exceptions in your implementation. In that case, you'd only include the @throws annotation in your doc block:</p>
<pre><code class="language-php">class AwesomeToaster implements ToasterInterface
{
    /**
     * @throws RuntimeException
     */
    public function toast(Bread $bread, $time) {}
}</code></pre>
<p>In case you want to override the short description, you can so so easily:</p>
<pre><code class="language-php">class AwesomeToaster implements ToasterInterface
{
    /**
     * Toast a white-bread.
     */
    public function toast(Bread $bread, $time) {}
}</code></pre>
<p>Let's come to the {@inheritDoc} inline annotation. First I have to clearify that you cannot override the long description without having a short description first. The {@inheritDoc} annotation is there to include the parent's long description, so you can actually use that one and extending it with your own documentation. In your case, this could look like this:</p>
<pre><code class="language-php">class AwesomeToaster implements ToasterInterface
{
    /**
     * Toast a white-bread.
     *
     * {@inheritDoc} It only accepts white-bread thought.
     */
    public function toast(Bread $bread, $time) {}
}</code></pre>
<p>There you go. We have the original description and on top of that our implementation-specific one. This would output like this:</p>
<pre><code class="language-html">Toast a white-bread.

This method will toast a bread for a given amount of seconds.
It only accepts white-bread thought.

    access: public

void toast (Bread $bread, int $time)

    Bread $bread
    int $time</code></pre>
<p>A last thing about overriding @param keywords. This is possible, but will make no sense most of the time, since a parent pretty much describes what the method should be able to take. In some cases you may want to widen the allowed range of values though. If that's the case, you only have to put the @param annotation for that single argument in your doc-block, and not repeat any of the other annotations.</p>
<p>I hope that this helps a few people to reduce the insaneness of way too much redundant and copy-pasted inline documentation and gives you a bit more time to actually produce awesome code.</p>
<p><strong>Update:</strong> I changed the Toast to Bread, based on Geeh's comment.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Zend Framework 2 Routing and Reverse Proxies</title>
      <description><![CDATA[I came about a pretty interesting routing scenario…]]></description>
      <pubDate>Fri, 11 Oct 2013 15:43:22 +0000</pubDate>
      <link>https://dasprids.de/blog/2013/10/11/zend-framework-2-routing-and-reverse-proxies/</link>
      <guid>https://dasprids.de/blog/2013/10/11/zend-framework-2-routing-and-reverse-proxies/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>I came about a pretty interesting routing scenario in #zftalk.dev which was not quite easy to solve, so I thought about writing a blog post about that. A user was using an HTTP reverse proxy with the following configuration:</p>
<pre><code class="language-httpd">ProxyPass /application/ http://www.example.com/
ProxyPassReverse /application/ http://www.example.com/</code></pre>
<p>As it turned out, reverse proxies will not pass any path information via headers, so this is not detectable at all. What's even worse is, that the matching works as expected, but the assembling will not have the path from the proxy included. This means that assembled URLs cannot be matched. Setting the base path to /myapplication/newpath/ doesn't work either, as matching will fail in that case then. The solution to the problem is a little bit dirty, but it should work in 99% of all cases. What you must basically do is allowing the router to do the matching with the detected base path, and afterwards set it to the proxy's path, so assembled URLs look correct. The problem with this approach is, that this only works with a single reverse proxy. As soon as you have more (for whatever reason), this will not work anymore. This is, as I wrote, because the reverse proxy does not pass any path information to the target server.</p>
<p>So after coming up with this idea, <a href="http://www.peterhough.co.uk/">Peter Hough</a>, who asked the question, worked out the code for this and supplied me the code for demonstration. The entire code is compressed into a single re-usable module, so everyone who needs it can just use it:</p>
<pre><code class="language-php">class Module
{
    /**
     * @param \Zend\Mvc\MvcEvent $e
     */
    public function onBootstrap(MvcEvent $e) {
        $eventManager = $e-&gt;getApplication()-&gt;getEventManager();

        // Trigger after matched route &amp; before authorization modules.
        $eventManager-&gt;attach(
            MvcEvent::EVENT_ROUTE,
            array($this, 'setBaseUrl'),
            -100
        );

        // Trigger before 404s are rendered.
        $eventManager-&gt;attach(
            MvcEvent::EVENT_RENDER,
            array($this, 'setBaseUrl'),
            -1000
        );
    }

    /**
     * Triggered after route matching to set the base URL for assembling with ProxyPass.
     *
     * @param \Zend\Mvc\MvcEvent $e
     */
    public function setBaseUrl(MvcEvent $e) {
        $request = $e-&gt;getRequest();
        $baseUrl = $request-&gt;getServer('APPLICATION_BASEURL');

        if (!empty($baseUrl) &amp;&amp; $request-&gt;getServer('HTTP_X_FORWARDED_FOR', false)) {
            $router = $e-&gt;getApplication()-&gt;getServiceManager()-&gt;get('Router');
            $router-&gt;setBaseUrl($baseUrl);
            $request-&gt;setBaseUrl($baseUrl);
        }
    }
}</code></pre>
<p>To enable the replacement, you have to set an environment variable named APPLICATION_BASEURL. If that one is not set or it is not a proxy request (accessing the application directly), nothing will happen. Setting the base URL is pretty simple.</p>
<p>Apache:</p>
<pre><code class="language-apache">SetEnv APPLICATION_BASEURL "/application/"</code></pre>
<p>nginx:</p>
<pre><code class="language-nginx">fastcgi_param APPLICATION_BASEURL /application/;</code></pre>
<p>Again, thanks to Peter Hough providing the code.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>QR-Code generation in PHP, now with bacon flavor</title>
      <description><![CDATA[
First of, this is not an April Fool's joke. I act…]]></description>
      <pubDate>Mon, 01 Apr 2013 18:23:49 +0000</pubDate>
      <link>https://dasprids.de/blog/2013/04/01/qr-code-generation-in-php-now-with-bacon-flavor/</link>
      <guid>https://dasprids.de/blog/2013/04/01/qr-code-generation-in-php-now-with-bacon-flavor/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<img itemprop="image" class="post-image" src="/images/content/posts/2013-04-01-bacon-qrcode.png" alt="Bacon QR-Code">
<p>First of, this is not an April Fool's joke. I actually planed to make one this year, but eventually gave up. Anyway, as some of you who follow me on Twitter may know, I worked on a modern QR-Code library, known as BaconQrCode, the past few weeks. Eventually it is now fully working and the public API can be considered stable.</p>
<p>As a base for my implementation I had choosen the <a href="http://code.google.com/p/zxing/">ZXing library</a> library. After writing the first unit tests though I noted that their implementation of the Reed-Solomon codec performed rather bad in PHP, so I exchanged it with the much faster implementation by <a href="http://www.ka9q.net/">Phil Karn</a>. As the rest of the library performed quite well and seemed much more logical, I choosed to stay with it instead of a different implementation like <a href="http://fukuchi.org/works/qrencode/">qrencode</a>, which formed the base for <a href="http://phpqrcode.sourceforge.net/">PHP QR Code</a>.</p>
<p>So far my complete implementation works, at least according to the unit tests and some personal testing. I'd like to encourage you to try it out and give me your feedback. I have implemented three different renderers so far, namely Bitmap (PNG), SVG and EPS. There is still a little bit of work to be done for me, like finishing the code-documentation, adding a few more unit tests and doing a few more PHP-specific optimizations, but all that work won't influence the public API anymore.</p>
<p>So, what are you waiting for? As always, you can find the library in the <a href="https://github.com/Bacon/BaconQrCode">Bacon repository on GitHub</a> or include it in your application via <a href="https://packagist.org/packages/bacon/bacon-qr-code">Packagist</a>. If you are interested in more cool stuff, check out the <a href="http://bacon.dasprids.de">website of of Bacon</a>.</p>
<p>Oh and before I forget it. I may also add QR-Code decoding in the future. This would really be a feature you won't find in any other QR-Code library for PHP ;)</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Sequel of the Internet Explorer hell</title>
      <description><![CDATA[Many of you may remember the &quot;good old days&q…]]></description>
      <pubDate>Sat, 15 Dec 2012 22:02:09 +0000</pubDate>
      <link>https://dasprids.de/blog/2012/12/15/sequel-of-the-internet-explorer-hell/</link>
      <guid>https://dasprids.de/blog/2012/12/15/sequel-of-the-internet-explorer-hell/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>Many of you may remember the &quot;good old days&quot;, when Windows XP came out which would let Joe Average be stuck with Internet Explorer 6 for a while, while finally giving him IE7, on which he'd be stuck for all eternity though, unless he'd upgrade to another browser like Firefox or Chrome. Surely, Joe Average may not know about these or be happy with this browser, which was very bad for us web developers. Eventually, the IE6 and IE7 were falling, and (depending on your business) we were able to drop support for those legacy browsers.</p>
<p>Everything seemed to be fine for the moment, until the prefix hell begun. But so far we were able to survive it, until recently browser vendors started to drop vendor prefixes on many key features (even IE9 came with a few unprefixed CSS3 features). Microsoft is also doing well with IE10, by implementing all those new CSS3 features without prefixes at all, following a recommendation from the CSS working group.</p>
<p>So, this basically sounds very exciting, but since we don't live in a perfect world, there's always some bad player; In this case it's Webkit. So far, less of the mostly used CSS3 features are available unprefixed in current, near future or farther future versions of Webkit, like background gradients, transitions and so on. But okay, we can live with this for now, it's just a single additional prefix, right?</p>
<p>Wrong! Do you remember the first paragraph, were I was talking about people with old operation systems and stock browsers? Well, the same thing is now repeating in the mobile world. For instance, the majority of Android users is stuck on Gingerbread (Android 2.3), which comes with a (relatively) very outdated stock browser, which even requires you to use an even older prefix with a different syntax for gradients. This forces us again to use a third version, which works completely different from the official and the newer webkit implementation.</p>
<p>Again, people could upgrade to a different browser (Firefox, Opera, …), but most simply don't care, because the browser works for them. What's the solution you may ask? Well, in my opinion, Google should handle the browser as any other app in the system and upgrade the Webkit base as often as they upgrade their desktop browser. Those are just my two cents, and I know that this action wouldn't change anything about the status quo, but could avoid the same problem in the future.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Slides for my internationalization talk</title>
      <description><![CDATA[I just uploaded my slides for my internationalizat…]]></description>
      <pubDate>Wed, 24 Oct 2012 21:21:58 +0000</pubDate>
      <link>https://dasprids.de/blog/2012/10/24/slides-for-my-internationalization-talk/</link>
      <guid>https://dasprids.de/blog/2012/10/24/slides-for-my-internationalization-talk/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>I just uploaded my slides for my internationalization talk at ZendCon. Again, please rate the talk on joind.in if you attended.</p>
<p><a href="http://stuff.dasprids.de/slides/zendcon2012/internationalization-in-zend-framework-2/presentation.html">http://stuff.dasprids.de/slides/zendcon2012/internationalization-in-zend-framework-2/presentation.html</a></p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Slides for my ZF2 router presentation</title>
      <description><![CDATA[I've just uploaded the slides for my ZF2 router pr…]]></description>
      <pubDate>Tue, 23 Oct 2012 21:57:38 +0000</pubDate>
      <link>https://dasprids.de/blog/2012/10/23/slides-for-my-zf2-router-presentation/</link>
      <guid>https://dasprids.de/blog/2012/10/23/slides-for-my-zf2-router-presentation/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>I've just uploaded the slides for my ZF2 router presentation for those wo are interested in them. You can find them right here on my website:</p>
<p><a href="http://stuff.dasprids.de/slides/zendcon2012/introducing-the-new-zend-framework-2-router/presentation.html">http://stuff.dasprids.de/slides/zendcon2012/introducing-the-new-zend-framework-2-router/presentation.html</a></p>
<p>For those who attended, please don't forget to rate the talk on joind.in: <a href="https://joind.in/6872">https://joind.in/6872</a></p>
<p>If you are interested in internationalization, you may join my talk tomorrow about i18n in ZF2.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Feeding Zend\I18n\Translator from a database</title>
      <description><![CDATA[Sometimes you need to get translation messages fro…]]></description>
      <pubDate>Thu, 23 Aug 2012 12:21:24 +0000</pubDate>
      <link>https://dasprids.de/blog/2012/08/23/feeding-zend-i18n-translator-from-a-database/</link>
      <guid>https://dasprids.de/blog/2012/08/23/feeding-zend-i18n-translator-from-a-database/</guid>
      <author>mail@dasprids.de (Ben Scholzen 'DASPRiD')</author>
      <dc:creator>Ben Scholzen 'DASPRiD'</dc:creator>
      <content:encoded><![CDATA[<p>Sometimes you need to get translation messages from a database, for instance when you want your clients to be able to add or edit translations. By default, this is not possible with the translator, but its extendibility allows you to easily integrate it.</p>
<p>Let's get started with the table layout. To get full support for all features, you will need two tables:</p>
<pre><code class="language-sql">CREATE TABLE `locales` (
  `locale_id` char(5) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  `locale_plural_forms` varchar(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  PRIMARY KEY (`locale_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `messages` (
  `message_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `locale_id` char(5) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  `message_domain` varchar(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  `message_key` text NOT NULL,
  `message_translation` text NOT NULL,
  `message_plural_index` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`message_id`),
  KEY `locale_id` (`locale_id`),
  KEY `message_domain` (`message_domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `messages`
  ADD CONSTRAINT `messages_ibfk_1`
  FOREIGN KEY (`locale_id`)
  REFERENCES `locales` (`locale_id`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;</code></pre>
<p>The first table is pretty easy to explain. It contains the 5-character locale (for instance: en-EN) and the definitions for the plural forms. The plural forms are defined the same way as they are in gettext and other formats.</p>
<p>The second table is not much more complex. It contains a primary integer key, a reference to the locale and the message specific data. Those are for once text domain, the key, so the string which you use in your source code, the translation for it and optionally the plural index, in case the translation requires plural forms. The plural index shoudl be equivalent with the result of the plural forms evaluation.</p>
<p>Now after we have created our table layout, we need to write a translation loader which is able to retrieve translations from the database. A very simple implementation with Zend\Db could look something like this:</p>
<pre><code class="language-php">&lt;?php
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Db\Sql\Sql;
use Zend\I18n\Translator\Loader\LoaderInterface;
use Zend\I18n\Translator\Plural\Rule as PluralRule;
use Zend\I18n\Translator\TextDomain;

class DatabaseTranslationLoader implements LoaderInterface
{
    protected $dbAdapter;

    public function __construct(DbAdapter $dbAdapter)
    {
        $this-&gt;dbAdapter = $dbAdapter;
    }

    public function load($filename, $locale)
    {
        $textDomain = new TextDomain();
        $sql        = new Sql($this-&gt;dbAdapter);

        $select = $sql-&gt;select();
        $select-&gt;from('locales');
        $select-&gt;columns(array('locale_plural_forms'));
        $select-&gt;where(array('locale_id' =&gt; $locale));

        $localeInformation = $this-&gt;dbAdapter-&gt;query(
            $sql-&gt;getSqlStringForSqlObject($select),
            DbAdapter::QUERY_MODE_EXECUTE
        );

        if (!count($localeInformation)) {
            return $textDomain;
        }

        $localeInformation = reset($localeInformation);

        $textDomain-&gt;setPluralRules(
            PluralRule::fromString($localeInformation['locale_plural_forms'])
        );

        $select = $sql-&gt;select();
        $select-&gt;from('messages');
        $select-&gt;columns(array(
            'message_key',
            'message_translation',
            'message_plural_index'
        ));
        $select-&gt;where(array(
            'locale_id'      =&gt; $locale,
            'message_domain' =&gt; $filename
        ));

        $messages = $this-&gt;dbAdapter-&gt;query(
            $sql-&gt;getSqlStringForSqlObject($select),
            DbAdapter::QUERY_MODE_EXECUTE
        );

        foreach ($messages as $message) {
            if (isset($textDomain[$message['message_key']])) {
                if (!is_array($textDomain[$message['message_key']])) {
                    $textDomain[$message['message_key']] = array(
                        $message['message_plural_index'] =&gt; $textDomain[$message['message_key']]
                    );
                }

                $textDomain[$message['message_key']][$message['message_plural_index']]
                    = $message['message_translation'];
            } else {
                $textDomain[$message['message_key']] = $message['message_translation'];
            }
        }

        return $textDomain;
    }
}</code></pre>
<p>This loader is a little bit tricky, as we are abusing the $filename parameter to pass in the text domain we want to load. Apart from that, the code should be pretty much self-explaining. Next you need to create a factory, so that the service manager can populate the loader with a database adapter when the translator requests an instance of the loader:</p>
<pre><code class="language-php">&lt;?php
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class DatabaseTranslationLoaderFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new DatabaseTranslationLoader(
            $serviceLocator-&gt;get('Zend\Db\Adapter\Adapter')
        );
    }
}</code></pre>
<p>Finally we can add the translations to our application:</p>
<pre><code class="language-php">&lt;?php
$translator-&gt;addTranslationFile(
    'DatabaseTranslationLoader',
    'text-domain',
    'text-domain'
);</code></pre>
<p>We have to enter the text domain twice here, as you read earlier we are abusing the $filename parameter to pass it to the loader. Now the translator is ready to use. You should make sure to use caching, as loading the translations on every request is kinda heavy. You'd usually choose a long caching time, and then simply invalidate the cache everytime the database translations are updated.</p>
<p>I hope this post will help all of you seeking for a solution to this problem. All code examples are written down out of my head, so they may contain mistakes or something may be missing at all. In that case please <a href="https://gist.github.com/">gist</a> me a corrected version of that part, so I can update it.</p>
<p>Be sure that more i18n related topics are following in the near future, and when you are going to <a href="http://www.zendcon.com">ZendCon</a>, don't miss my <a href="http://zendcon.com/sessions/?tid=2622#session-22628">i18n</a> or <a href="http://zendcon.com/sessions/?tid=2622#session-22627">router</a> talk there!</p>
<p><strong>Update:</strong> I'm currently working on a database translation loader added to ZF2 itself. It will most likely be available in 2.1.</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
  </channel>
</rss>

