<?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>James Halsall</title> <atom:link href="http://jameshalsall.co.uk/feed/" rel="self" type="application/rss+xml" /><link>http://jameshalsall.co.uk</link> <description>Ramblings of a web developer.</description> <lastBuildDate>Sat, 04 May 2013 09:51:41 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <item><title>Truncating Data via Doctrine 2.x in MySQL</title><link>http://jameshalsall.co.uk/truncating-data-via-doctrine-2-x-in-mysql/</link> <comments>http://jameshalsall.co.uk/truncating-data-via-doctrine-2-x-in-mysql/#comments</comments> <pubDate>Tue, 26 Feb 2013 20:55:22 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=70</guid> <description><![CDATA[I recently stumbled across a question on stackoverflow.com where somebody was having problems with foreign key constraints and truncating data in MySQL. An accepted answer stated that while it was possible to truncate the data, it isn&#8217;t possible if there are foreign keys present (as is the case with Doctrine 2 entities). Actually, it is [...]]]></description> <content:encoded><![CDATA[<p>I recently stumbled across a question on stackoverflow.com where somebody was having problems with foreign key constraints and truncating data in MySQL. An accepted answer stated that while it was possible to truncate the data, it isn&#8217;t possible if there are foreign keys present (as is the case with Doctrine 2 entities).</p><p><span
id="more-70"></span></p><p>Actually, it is possible to truncate your data even with foreign key constraints. It can be dangerous&nbsp;if you&#8217;re not careful about what you delete, but the following code can be useful in Doctrine 2.x if you have a need for emptying tables programmatically:</p> <script src="http://gist.github.com/4b230c0022c59e623f43.js"></script> <p>The raw query before and after the truncate statement tells MySQL to forget about foreign key constraints, so it just blindly empties your table(s). Hopefully this will save people some time.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/truncating-data-via-doctrine-2-x-in-mysql/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Glob Performance for Finding Files in PHP</title><link>http://jameshalsall.co.uk/glob-performance-for-finding-files-in-php/</link> <comments>http://jameshalsall.co.uk/glob-performance-for-finding-files-in-php/#comments</comments> <pubDate>Sat, 01 Dec 2012 15:31:45 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=67</guid> <description><![CDATA[Listing files in a directory isn&#8217;t something that I&#8217;d usually worry about in a web application, considering that its usually inside a CMS or a limited-access backend where the number of daily requests are in the hundreds rather than millions. Recently however, when working on a large-scale website for a client I started thinking about [...]]]></description> <content:encoded><![CDATA[<p>Listing files in a directory isn&#8217;t something that I&#8217;d usually worry about in a web application, considering that its usually inside a CMS or a limited-access backend where the number of daily requests are in the hundreds rather than millions. Recently however, when working on a large-scale website for a client I started thinking about the performance differences between <code>glob</code> and <code>opendir</code>/<code>readdir</code> in PHP 5.3. I&#8217;ve always used <code>glob</code>, just because it makes life easier with partial string matching and because it returns your file paths in an array ready to use, but not because I thought it was drastically better in terms of performance.<span
id="more-67"></span></p><h2>Listing Files in glob vs opendir</h2><p>Its worth mentioning that glob and <code>opendir</code>/<code>readdir</code> are very different entry-points for file management. The former is solely used to list files that match a given pattern string. For example, <code>glob('/tmp/*.php')</code> will return an array containing all files in the system&#8217;s /tmp directory that have a .php extension. With <code>opendir</code>/<code>readdir</code> however, a file resource handle is returned which allows further file manipulation. This can be powerful in its own right, but if its simple file listing that you want then <code>opendir</code>/<code>readdir</code> isn&#8217;t the right tool for the job and here&#8217;s a good reason why.</p><h2>Performance</h2><p>The performance gain from using glob and <code>opendir</code>/<code>readdir</code> are quite vast. The <a
title="Glob Benchmark" href="https://github.com/jaitsu87/php-benchmarks/tree/master/FindPhpFiles" target="_blank">benchmark we used</a> created a mixture of 2000 PHP, text and CSV files inside a directory already containing hundreds of other files (it used the system&#8217;s /tmp directory where a lot of logging and system dump files are placed). We then used each approach in turn, recording the time before and after the process and also purging the files in the directory between each run so that the operating system&#8217;s disk cache&#8217;s were cold between runs.</p><p>The results are shown below, with the numbers representing an average over 10 individual tests. We used Ubuntu Server 64-bit as our platform of choice, although running it on other distros and operating systems proved to result in the same outcome. We were not able to benchmark performance on Windows as we didn&#8217;t have an install available, although it would interesting to see how their <code>cmdlet</code> implementation performs compared to a true <code>glob</code>.</p><h3>Time based performance:</h3><p>Using <code>glob</code>: 0.006263 seconds<br
/> Using <code>opendir</code>/<code>readdir</code>: 0.30983 seconds</p><h3>Memory based performance:</h3><p>Using <code>glob</code>: 1.227562 MB<br
/> Using <code>opendir</code>/<code>readdir</code>: 1.149849 MB</p><p>Whilst memory usage is a fraction more, the gain in processing time is nearly 5 times quicker. In terms of request time, that&#8217;s quite a big difference. If you&#8217;re using <code>opendir</code>/<code>readdir</code> to list files in your web application, you are doing it wrong.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/glob-performance-for-finding-files-in-php/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Laziness, it hurts us all</title><link>http://jameshalsall.co.uk/laziness-it-hurts-us-all/</link> <comments>http://jameshalsall.co.uk/laziness-it-hurts-us-all/#comments</comments> <pubDate>Thu, 20 Sep 2012 19:13:19 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Uncategorized]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=59</guid> <description><![CDATA[I&#8217;ve been thinking a lot lately about what separates the bad lazy programmers from the good enthusiastic ones. There will always be the genuinely gifted developers who are one in a million, but what separates you from the pack if you&#8217;re not one of these people? I don&#8217;t think it&#8217;s so much to do with ability [...]]]></description> <content:encoded><![CDATA[<p>I&#8217;ve been thinking a lot lately about what separates the <del>bad</del> lazy programmers from the <del>good</del> enthusiastic ones. There will always be the genuinely gifted developers who are one in a million, but what separates you from the pack if you&#8217;re not one of these people? I don&#8217;t think it&#8217;s so much to do with ability as much as it is enthusiasm, energy and a passion for self-development.<span
id="more-59"></span></p><h2>Documenting</h2><p>If you asked 1000 programmers for their thoughts on writing documentation, I bet you&#8217;d struggle to find 5 who say they enjoy it. Documentation is always an after thought, and something that many popular open source projects massively overlook (just take a look at <a
title="Zend Cache Documentation" href="http://framework.zend.com/manual/2.0/en/modules/zend.cache.storage.adapter.html">ZF2&#8242;s documentation on caching</a>). I believe that good documentation starts from the very first line of code. If we&#8217;re creating a new class, then we should be making starting with a class doc comment that is well rounded and thoroughly explains to the viewer what this class and its instances represent in the application. Whilst this seems like basic common sense to most developers, the number of classes that I come across with <strong>zero</strong> documentation which have been written by talented developers is bemusing.</p><p>Consider the following extrapolated example from <a
title="Tickit" href="http://gettickit.com">Tickit</a>&#8230;</p><pre class="brush: php; title: ; notranslate">
&lt;?php
//...
class Configuration implements ConfigurationInterface
{
    //...
}
?&gt;
</pre><p>Above is what I seem to come across 9 times out of 10 when I open up a file. What does this class actually do? Configuration is semantically vague at this point, does it represent a set of configuration values? Does it process configuration values or does it hand them off to another class? We could always trawl through the implementation details of the class but this leaves puts a lot of work back on the maintainer, and so much information is lost between implementation and maintenance. The best person to document the class is the creator.</p><pre class="brush: php; title: ; notranslate">
&lt;?php
//...
/**
 * Reads and processes configuration information for the cache bundle
 *
 * @author James Halsall &lt;james.t.halsall@googlemail.com&gt;
 */
class Configuration implements ConfigurationInterface
{
    //...
}
?&gt;
</pre><p>This example now gives us a little bit more information about what the class does and, whilst not perfect it gives the maintainer a quick overview of the class and whether or not this is what they&#8217;re looking for.</p><p>We could say that method documentation is even more important in some ways. Let&#8217;s suppose we have a method that carries out the following process after a member logs out&#8230;</p><ul><li>Clears the $_SESSION</li><li>Removes client cookies</li><li>Deletes the user&#8217;s row from user_session table in the database</li></ul><p>If we document properly then should something not be working quite right at least the maintainer has a point of reference for what this method <strong>should</strong> be doing. In contrast, if we hadn&#8217;t bothered to write a doc block for the method then our maintainer would have to start stepping through code to find out why the user hadn&#8217;t been logged out properly. Whilst debugging is part of a developer&#8217;s repertoire, why should we make the lives of a maintainer more difficult than necessary?</p><h2>Exceptions</h2><p>PHP has a decent standard library of exceptions, ranging from the base <a
title="PHP Exception" href="http://uk3.php.net/manual/en/class.exception.php">Exception</a> class to the <a
title="PHP BadMethodCallException" href="http://php.net/manual/en/class.badmethodcallexception.php">BadMethodCallException</a> and <a
title="PHP RuntimeException" href="http://php.net/manual/en/class.runtimeexception.php">RuntimeException</a>. Yet even though we have these &#8220;ready made&#8221; exception classes providing semantic value, many developers seem to think the base Exception class is the only one to throw when something goes wrong.</p><p>An example demonstrates the difference in readability between using correct the base Exception class as opposed to more semantically valid exceptions.</p><pre class="brush: php; title: ; notranslate">
&lt;?php
    try {
        $params = array(/* some values */);
        $db = $this-&gt;db-&gt;connect($params);
    } catch (Exception $e) {
        // something went wrong, not sure without seeing the exception message
    }
</pre><p>From this snippet, it is difficult to immediately see what could possibly go wrong inside the connect method. We know that we&#8217;ll catch the Exception, but how do we display a decent error message to the client if we don&#8217;t have some more semantic information about what went wrong? Was it a problem connecting to the database? Or did we pass an array when we should have passed a string as the argument?</p><p>Here&#8217;s the same piece of code, but with better exceptions being used&#8230;</p><pre class="brush: php; title: ; notranslate">
&lt;?php
    try {
        $params = array(/* some values */);
        $db = $this-&gt;db-&gt;connect($params);
    } catch (InvalidArgumentException $e) {
        //oops, passed in an invalid parameter
    } catch (RuntimeException $e) {
        //oops, a bad configuration value somewhere
    } catch (DatabaseConnectionException $e) {
       // can't connect to the database
    }
</pre><h2></h2><p>In this second snippet we can immediately see that we expect three things to (potentially) go wrong. The first is an <code>InvalidArgumentException</code>, which indicates that some value passed into the connect method is illegal. The second is the <code>RuntimeException</code>, which means we can&#8217;t realistically recover from it and in this case indicates that some database setting in the application configuration is wrong. The final exception is a custom <code>DatabaseConnectionException</code> class, which might be thrown when the database is unreachable.</p><h2>Error Messages</h2><p>Readability applies with error messages as well as the chosen exception classes. If we attempt to write to a file cache and something goes wrong, our error message should be providing enough information to directly pinpoint the problem. There are always cases where something may happen that we haven&#8217;t accounted for, but these will usually be due to a change in behaviour of a third party library or an upgrade in PHP. They are few and far between in most dynamic applications, so we should endeavour to write informative error messages.</p><p>Consider an example I came across recently&#8230;</p><pre class="brush: php; title: ; notranslate">
&lt;?php
    //...
    try {
        $cache = new FileCache();
        $cache-&gt;write(/* some variables */);
    } catch (Exception $e) {
        die('Cache not writable');
    }
</pre><p>Whilst this is quite an abstract example, there is so much wrong with this exception handling that it would be better off if it hadn&#8217;t been caught at all. Exceptions should only be caught and handled under two situations&#8230;</p><ol><li>We can programmatically recover from the thrown exception, or..</li><li>We can provide a better exception message to the developer / user</li></ol><p>Neither of these are true in this example (which I came across on a fairly large scale website recently), which is what makes it so terrible. A better way to handle this would have been&#8230;</p><pre class="brush: php; title: ; notranslate">
&lt;?php
    //...
    try {
        $cache = new FileCache();
        $cache-&gt;write(/* some variables */);
    } catch (Exception $e) {
        die(sprintf('The file cache cannot write to %s', $cache-&gt;getCacheDir()));
    }
</pre><p>Obviously the better approach would be to not even catch the exception at all (providing that the <code>FileCache</code> is throwing an exception with a helpful message itself).</p><h2>Wrap Up</h2><p>Writing better code doesn&#8217;t just mean solving a problem in the least amount of lines, or using triple nested ternary statements as though no other programmer would ever have to read the code ever again (this is also something I&#8217;ve seen recently). Just by documenting, picking proper exception classes, writing better error messages and always thinking about readability we can immediately create a more maintainable application or website without having even touched unit testing or mess detection (which we should all be doing by now). These things might take that bit more of our time, but without being selfish we enable maintainers to be more productive much quicker.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/laziness-it-hurts-us-all/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Installing ImageMagick beta for PHP on Ubuntu</title><link>http://jameshalsall.co.uk/installing-imagemagick-beta-for-php-on-ubuntu/</link> <comments>http://jameshalsall.co.uk/installing-imagemagick-beta-for-php-on-ubuntu/#comments</comments> <pubDate>Sun, 06 May 2012 13:14:53 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Server Administration]]></category> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=57</guid> <description><![CDATA[There seems to be a few issues with Imagick in PECL related to setting your own properties on a class that extends Imagick. A project I&#8217;m working on at the moment is making heavy use of image processing and I wanted to stick with Imagick over the GD library. A little bit of investigation told [...]]]></description> <content:encoded><![CDATA[<p>There seems to be a few issues with Imagick in PECL related to setting your own <a
title="PHP properties bug when extending Imagick class" href="https://bugs.php.net/bug.php?id=59565">properties on a class</a> that extends Imagick. A project I&#8217;m working on at the moment is making heavy use of image processing and I wanted to stick with Imagick over the GD library. A little bit of investigation told me that this bug was fixed in the latest release candidate of Imagick in PECL, so I began investigating how to install a beta release of the extension but Google gave me no hits.</p><p><span
id="more-57"></span></p><p>Turns out that it was pretty straight forward, and it seems to have resolved my issues. These are the steps I took to <strong>update </strong>my installation of PECL Imagick, but they should work if you have the Imagick core library on your system and are just in need of the PHP extension for it.</p><pre class="brush: bash; title: ; notranslate">
cd ~/
wget http://pecl.php.net/get/imagick-3.1.0RC1.tgz
cd imagick-3.1.0RC1
./configure --prefix=/usr/lib --with-bzlib=yes --with-fontconfig=yes --with-freetype=yes --with-gslib=yes --with-gvc=yes --with-jpeg=yes --with-jp2=yes --with-png=yes --with-tiff=yes
sudo make
sudo make install
vim /etc/php5/conf.d/imagick.ini (add the line &quot;extension=imagick.so&quot;)
sudo /etc/init.d/apache2 reload
</pre><p>To verify your installation, you should have the &#8220;imagick.so&#8221; extension file in <code>/usr/lib/php5/20090626</code>.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/installing-imagemagick-beta-for-php-on-ubuntu/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Recording &#8216;Last Activity&#8217; for Users in Symfony2 + FOSUserBundle</title><link>http://jameshalsall.co.uk/recording-last-activity-for-users-in-symfony2-fosuserbundle/</link> <comments>http://jameshalsall.co.uk/recording-last-activity-for-users-in-symfony2-fosuserbundle/#comments</comments> <pubDate>Fri, 27 Jan 2012 19:50:54 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=52</guid> <description><![CDATA[Whilst working on a personal project based on the Symfony2 framework I wanted to record when a user was last active so that I could emulate a list of currently online users. I had already plugged in the amazing FOSUserBundle extension, so this was just about tweaking what was already there. If you&#8217;re in a [...]]]></description> <content:encoded><![CDATA[<p>Whilst working on a personal project based on the Symfony2 framework I wanted to record when a user was last active so that I could emulate a list of currently online users. I had already plugged in the amazing <a
href="https://github.com/FriendsOfSymfony/FOSUserBundle">FOSUserBundle</a> extension, so this was just about tweaking what was already there. If you&#8217;re in a similar situation and already have the Symfony2 standard distribution installed with FOSUserBundle then this walkthrough should be pretty straightforward.<span
id="more-52"></span></p><h2>Utilising Symfony2&#8242;s Event Model</h2><p>Symfony2 has a great plethora of internal events that you can &#8216;hook&#8217; into. In our case, we want to hook into a kernel event called which will fire whenever a request is made by the client browser. In your User bundle, create a <code>services.yml</code> file (e.g. <code>src/App/UserBundle/Resources/config/services.yml</code>) as follows:</p><pre class="brush: plain; title: ; notranslate">
services:
  activity_listener:
    class: App\UserBundle\Listener\Activity
    arguments: [@security.context, @doctrine]
    tags:
      - { name: kernel.event_listener, event: kernel.controller, method: onCoreController }
</pre><p>This is quite straightforward, this is just telling our application that when the <code>kernel.controller</code> event is fired we want our kernel to also call the <code>onCoreController()</code> method in our <code>App\UserBundle\Listener\Activity</code> class (we&#8217;ll create that in a minute). Before we move on to creating our event handler class we need to register our <code>services.yml</code> file with our main kernel. We can do this by editing <code>app/config/config.yml</code> and adding an <code>import</code> directive at the top of the file&#8230;</p><pre class="brush: plain; title: ; notranslate">
imports:
    - { resource: @AppUserBundle/Resources/config/services.yml }
</pre><h2>The Event Handler Class</h2><p>Now we have to create our event handler class, which will do most of the work. I decided to call my class <code>Activity</code>, but you can call it whatever you like as long as you make sure to amend your <code>services.yml</code> file to contain the same name. Our file will reside at <code>src/UserBundle/Listener/Activity.php</code>&#8230;</p><pre class="brush: php; title: ; notranslate">
namespace App\UserBundle\Listener;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\DoctrineBundle\Registry as Doctrine;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use DateTime;
use App\UserBundle\Entity\User;
class Activity
{
    protected $context;
    protected $em;
    public function __construct(SecurityContext $context, Doctrine $doctrine)
    {
        $this-&gt;context = $context;
        $this-&gt;em = $doctrine-&gt;getEntityManager();
    }
    /**
     * On each request we want to update the user's last activity datetime
     *
     * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event
     * @return void
     */
    public function onCoreController(FilterControllerEvent $event)
    {
        $user = $this-&gt;context-&gt;getToken()-&gt;getUser();
        if($user instanceof User)
        {
            //here we can update the user as necessary
            $user-&gt;setLastActivity(new DateTime());
            $this-&gt;em-&gt;persist($user);
            $this-&gt;em-&gt;flush($user);
        }
    }
}
</pre><p>Be sure to update your <code>User</code> class with the correct properties (e.g. <code>last_activity</code>) in order for the setters to work and you&#8217;re away.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/recording-last-activity-for-users-in-symfony2-fosuserbundle/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>robbailey.co.uk is live</title><link>http://jameshalsall.co.uk/robbailey-co-uk-is-live/</link> <comments>http://jameshalsall.co.uk/robbailey-co-uk-is-live/#comments</comments> <pubDate>Fri, 02 Dec 2011 19:35:21 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Portfolio]]></category> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=50</guid> <description><![CDATA[I&#8217;ve recently finished working on a new website for UK based artist and illustrator Rob Bailey. You should definitely head over and check out his work at robbailey.co.uk.]]></description> <content:encoded><![CDATA[<p>I&#8217;ve recently finished working on a new website for UK based artist and illustrator Rob Bailey. You should definitely head over and check out his work <a
href="http://robbailey.co.uk" title="Rob Bailey's website">at robbailey.co.uk</a>.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/robbailey-co-uk-is-live/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Doctrine 1.2, SQL Server, FreeTDS and Hanging Queries</title><link>http://jameshalsall.co.uk/doctrine-1-2-sql-server-and-hanging-queries-in-freetds/</link> <comments>http://jameshalsall.co.uk/doctrine-1-2-sql-server-and-hanging-queries-in-freetds/#comments</comments> <pubDate>Wed, 19 Oct 2011 20:56:25 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Database Administration]]></category> <category><![CDATA[Server Administration]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=47</guid> <description><![CDATA[It&#8217;s been a somewhat turbulent few days in the office this week, working with Doctrine 1.2 and SQL Server is no joke. Seriously, there are several flaws in Doctrine&#8217;s MS SQL parsing engine which just make me think that they have never bothered to test. One of these issues only occurred when using two LIKE [...]]]></description> <content:encoded><![CDATA[<p>It&#8217;s been a somewhat turbulent few days in the office this week, working with Doctrine 1.2 and SQL Server is no joke. Seriously, there are several flaws in Doctrine&#8217;s MS SQL parsing engine which just make me think that they have never bothered to test.</p><p><span
id="more-47"></span></p><p>One of these issues only occurred when using two <code>LIKE</code> conditions in the <code>WHERE</code> clause. Another issue was caused when having multiple <code>SUM</code> methods in the <code>SELECT</code>, aliasing them and then using the alias name in the <code>WHERE</code> clause. The result was a broken query, a very basic syntax error you think Doctrine engineers would have tackled from early on.</p><p>I&#8217;m not naive though, it&#8217;s probably too much to expect to have PDO working nicely with SQL Server, especially seeing as the defacto driver is still <a
title="PHP's PDO Dblib driver" href="http://php.net/manual/en/ref.pdo-dblib.php">marked as experimental</a> in the PHP API.</p><p>If you&#8217;re <del>unlucky</del> lucky enough to get the chance to work with SQL Server and Doctrine, then you&#8217;ll be aware of the issues that plague the library, it&#8217;s something I expect Doctrine to have resolved in version 2 of their ORM.</p><h2>FreeTDS</h2><p>Not all of the blame lies at the door of Doctrine, sure it has it&#8217;s parse engine errors, but there are times when the driver is clearly not working as it should.</p><p>PDO_DBLIB uses <a
title="PHP's Sybase API entry" href="http://php.net/manual/en/book.sybase.php">Sybase</a> and <a
title="FreeTDS homepage" href="http://www.freetds.org/">FreeTDS</a> to connect and communicate with SQL Server. The configuration is quite simple, and although you have to compile from source on older platforms it is usually available through a package manager such as <code>apt-get</code> or <code>yum</code>. The biggest headache came last week, when queries executed directly via PDO (bypassing Doctrine&#8217;s DQL) where hanging unexpectedly. No server output, no exceptions&#8230; nothing. Checking logs didn&#8217;t help either, it seemed as though PHP&#8217;s call stack fell into a bottomless pit as soon as PDO executed a query. Articles online didn&#8217;t help, suggesting that moving to use the <a
title="James Rossiter\'s blog entry on PHP, ODBC and SQL Server" href="http://jamesrossiter.wordpress.com/2011/03/08/connecting-to-microsoft-sql-server-using-odbc-from-ubuntu-server/">ODBC driver is a better solution</a> (I personally disagree, and think that the ODBC driver can be even more flaky).</p><h2>Solving Hanging Queries</h2><p>The FreeTDS config file is made up of several host blocks, which allow you to hand off the connection configuration to the FreeTDS library and allow PHP to simply connect to a host name. A host block looks something like as follows&#8230;</p><p><code>[sqlserver2]<br
/> host = 192.168.1.14<br
/> port = 1433<br
/> tds version = 5.0<br
/> </code></p><p>The magic configuration option I was missing in the host block was <code>initial block size</code>. In the official documentation it is referred to as &#8220;the initial protocol block size&#8221;, which basically means how big a block of data the established socket will transmit. For some reason, the default setting of <code>512</code> was causing the hanging queries (in fact, when checking the FreeTDS debug log, it was terminating the connection internally but not relaying it back to PHP &#8211; hence the hang). However, by increasing this block size in increments of 512 and re-testing the faulting queries I was able to find an optimum setting of 1536, which resolved the issue.</p><p>All in all? Try to avoid Doctrine and SQL Server where you can. Although Doctrine 2 should provide better support (in theory), it will still be reliant on the PDO_DBLIB or PDO_ODBC drivers&#8230; both of which have their fair share of problems.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/doctrine-1-2-sql-server-and-hanging-queries-in-freetds/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Custom ExtJS Grid Context Menus</title><link>http://jameshalsall.co.uk/custom-extjs-grid-context-menus/</link> <comments>http://jameshalsall.co.uk/custom-extjs-grid-context-menus/#comments</comments> <pubDate>Sat, 25 Jun 2011 18:51:12 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=40</guid> <description><![CDATA[ExtJS provides some powerful grid functionality with their Ext.grid package, and part of this functionality includes custom context menus that provide an intuitive method of interaction with grid rows. I found that there was no documentation on how to create these menus, so I thought I would put together a quick tutorial. I&#8217;m assuming that [...]]]></description> <content:encoded><![CDATA[<p>ExtJS provides some powerful grid functionality with their <code>Ext.grid</code> package, and part of this functionality includes custom context menus that provide an intuitive method of interaction with grid rows. I found that there was no documentation on how to create these menus, so I thought I would put together a quick tutorial. I&#8217;m assuming that users have a basic understanding of ExtJS, and the version I am using as a demonstration is ExtJS 3.4.</p><p><span
id="more-40"></span></p><p>Assuming you already have a grid panel (<code>Ext.grid.GridPanel</code> or <code>Ext.grid.EditorGridPanel</code>) setup, we need to add in an event listener to help with our context menu creation. <code>Ext.grid.GridPanel</code> has several listeners available to help with this, these are</p><ul><li><code>rowbodycontextmenu</code></li><li><code>rowcontextmenu</code></li></ul><p>Both of these events are fired when the user right-clicks on a row in the grid, but the first of them requires the optional config <code>enableRowBody</code> being set to <code>true</code> in the grid&#8217;s <code>GridView</code>. We will use the latter, as we&#8217;re assuming that we&#8217;re not in need of any special grid row manipulation (hooking into both of these events would prove a better option if you&#8217;re using the <code>enableRowBody</code> config). Our <code>Ext.grid.GridPanel</code> code may now look something like this&#8230;</p><pre class="brush: jscript; title: ; notranslate">
var grid = new Ext.grid.GridPanel({
   border: false,
   title: 'Sample Grid',
   loadMask: true,
   viewConfig: {
       forceFit: true,
       autoFill: true
   },
   ds: new Ext.data.JsonStore({ ... }),
   cm: new Ext.grid.ColumnModel({ ... }),
   sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
   listeners: {
       'rowcontextmenu' : function(grid, index, event) {
            //do something
       }
   }
});
</pre><p>You may notice that we&#8217;ve added three arguments to our <code>rowcontextmenu</code> event handler function. These are</p><ul><li><code>grid</code> &#8211; The <code>Ext.grid.GridPanel</code> that we&#8217;re tying into</li><li><code>index</code> &#8211; The row index that we right-clicked on</li><li><code>event</code> &#8211; The right-click event object, containing useful information about what we right clicked</li></ul><p>The next step is to create a function that will generate our context menu when we perform the right click, obviously this will be called from within our <code>rowcontextmenu</code> event handler. In our menu we will add items that will alert some information from our grid&#8217;s store. This will look something like below&#8230;</p><pre class="brush: jscript; title: ; notranslate">
function showMenu(grid, index, event) {
      event.stopEvent();
      var record = grid.getStore().getAt(index);
      var menu = new Ext.menu.Menu({
            items: [{
                text: 'Show Job ID',
                handler: function() {
                    alert(record.get('job_id'));
                }
            }, {
                text: 'Show Customer',
                handler: function() {
                    alert(rec.get('customer_name'));
                }
            }]
        }).showAt(event.xy);
}
</pre><p>Firstly, we create an <code>Ext.menu.Menu</code> object that will contain our menu items, and then we add our items in line by using the <code>items</code> config. The last part of this function uses the <code>showAt</code> method on our menu object. This tells ExtJS to show the menu at a specific set of X and Y coordinates as specified in our click event. The last thing for us to do is tie our function into the event handler we specified on our grid earlier&#8230;</p><pre class="brush: jscript; title: ; notranslate">
listeners: {
    'rowcontextmenu' : function(grid, index, event) {
         showMenu(grid, index, event);
    }
}
</pre><p>Now when we right click on our grid&#8217;s data, we should see something similar to this&#8230;<br
/><div
id="attachment_41" class="wp-caption alignright" style="width: 160px"><a
href="http://jameshalsall.co.uk/wp-content/uploads/2011/06/extjscontextmenu.png"><img
src="http://jameshalsall.co.uk/wp-content/uploads/2011/06/extjscontextmenu.png" alt="" title="extjscontextmenu" width="150" height="103" class="size-full wp-image-41" /></a><p
class="wp-caption-text">A sample ExtJS right-click context menu</p></div></p><p>Whilst this is a simple example of context menus, it provides a very quick insight into how easy it is to achieve desktop-like experiences using ExtJS. If you have any questions, don&#8217;t hesitate to get in touch.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/custom-extjs-grid-context-menus/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>Missing mysql.sock file in ZendServer (Mac OSX)</title><link>http://jameshalsall.co.uk/missing-mysql-sock-file-in-zendserver-mac-osx/</link> <comments>http://jameshalsall.co.uk/missing-mysql-sock-file-in-zendserver-mac-osx/#comments</comments> <pubDate>Fri, 17 Jun 2011 23:00:12 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Database Administration]]></category> <category><![CDATA[Server Administration]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=39</guid> <description><![CDATA[I have spent the best part of today tearing my hair out, trying to figure out why the mysql.sock socket file was missing from my clean ZendServer CE install. From googling a little on the subject it seems I am not the only one to suffer this fate. Turns out that none of the solutions [...]]]></description> <content:encoded><![CDATA[<p>I have spent the best part of today tearing my hair out, trying to figure out <strong>why</strong> the mysql.sock socket file was missing from my <em>clean</em> ZendServer CE install. From googling a little on the subject it seems <a
href="http://macosx.com/forums/mac-os-x-system-mac-software/2863-mysql-dead-mysql-sock-missing.html">I am not</a> the only one to <a
href="http://www.botsko.net/blog/2009/03/16/missing-mysqlsock-on-mac-os-x/">suffer this fate</a>. Turns out that none of the solutions suggested in these articles applied for me.</p><p><span
id="more-39"></span></p><p>A few weeks back, when I got my brand new MacBook Pro I decided to play around with ZendServer, and ended up changing things so much that I decided to just do a clean install. So I followed Zend&#8217;s method of <a
href="http://files.zend.com/help/Zend-Server-Community-Edition/mac_osx_installation.htm#MiniTOCBookMark5">uninstalling the server</a> and proceeded to install my new, fresh copy. I was a little surprised when I was receiving errors from my mysql instance&#8230;</p><blockquote><p>ERROR 2002: Can&#8217;t connect to local MySQL server through socket &#8216;/tmp/mysql.sock&#8217; (2)</p></blockquote><p>I did a little digging around my Mac, I tried running a find..</p><pre class="brush: bash; title: ; notranslate">
sudo find / -name mysql.sock
</pre><p>But this returned nothing. The mysql.sock file is apparently located at <code>/usr/local/zend/mysql/tmp/mysql.sock</code> or alternatively <code>/tmp/mysql.sock</code>, but mine had vanished from the file system completely. After a little digging, I found a shell script bundled in with ZendServer, <code>/usr/local/zend/bin/uninstall.sh</code>. Running this script cleaned out my current installation and after performing another clean install of ZendServer I had my mysql.sock file back where it should have been.</p><p>It&#8217;s pretty strange as to why Zend haven&#8217;t updated their instructions for removing ZendServer correctly, and it can potentially cause a lot of issues if you&#8217;re hoping to use mysql in the future.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/missing-mysql-sock-file-in-zendserver-mac-osx/feed/</wfw:commentRss> <slash:comments>12</slash:comments> </item> <item><title>Custom Event Rendering with Ext Calendar Pro</title><link>http://jameshalsall.co.uk/custom-event-rendering-with-ext-calendar-pro/</link> <comments>http://jameshalsall.co.uk/custom-event-rendering-with-ext-calendar-pro/#comments</comments> <pubDate>Mon, 13 Jun 2011 19:45:02 +0000</pubDate> <dc:creator>James Halsall</dc:creator> <category><![CDATA[Web Development]]></category> <guid
isPermaLink="false">http://jameshalsall.co.uk/?p=35</guid> <description><![CDATA[ExtJS is a great framework, and whilst its learning curve is quite steep it makes building user interfaces as simple as you could hope for. One of its major let-downs however, is its lack of Calendar component (quite a frequently requested interface layout actually). Brian Moeskau (one of the earlier developers in the ExtJS project) [...]]]></description> <content:encoded><![CDATA[<p>ExtJS is a great framework, and whilst its learning curve is quite steep it makes building user interfaces as simple as you could hope for. One of its major  let-downs however, is its lack of Calendar component (quite a frequently requested interface layout actually). Brian Moeskau (one of the earlier developers in the ExtJS project) released his own 3rd Party extension called <a
href="http://ext.ensible.com/products/calendar/">Ext Calendar Pro</a>, which fills this void.</p><p><span
id="more-35"></span></p><p
style='font-size: 1.1em;'>Just a quick note on the following post, I am assuming that the user already has basic knowledge of the Ext Calendar Pro component, and that they have a simple example already working.</p><p>Recently on a work project I was required to create a Calendar based interface for controlling which staff are on-call for specific days. I was a little confused at how you could go about adding custom fields and rendering calendar events differently using Ext Calendar Pro, so I did a bit of digging through the source code and thought I would share my findings here and save someone else some time.</p><p>The Calendar component uses store mappings to let the developer map custom fields in the calendar&#8217;s <code>eventstore</code> to server-side fields (sent from the <code>HttpProxy</code>). For each custom field in an event record in the calendar you must specify the custom mapping. To specify our mappings we must modify the <code>Ext.ensible.cal.EventMappings</code> object directly <strong>before</strong> we create our Calendar. For example, if we wanted to store a custom field on each event which would record the employee&#8217;s name, we would create a mapping as follows&#8230;</p><pre class="brush: jscript; title: ; notranslate">
Ext.ensible.cal.EventMappings.EmployeeName = {
    name: 'EmployeeName', //name in the store
    mapping: 'employee_name', //the server-side field name
    type: 'string'
};
Ext.ensible.cal.EventRecord.reconfigure();
</pre><p>Theoretically we could add as many custom field mappings as we wanted to this way. If we&#8217;re modifying a lot of the mappings it can sometimes be easier to completely override the <code>EventMappings</code> object and redefine it to include only fields we require. For example, if the only fields we wanted to record were a description, start time, end time and employee name then we could override the <code>EventMappings</code> object as follows&#8230;</p><pre class="brush: jscript; title: ; notranslate">
Ext.ensible.cal.EventMappings = {
      EventId:                {name: 'event_id', mapping:'event_id', type:'int'},
      Description:         {name: 'description', mapping: 'description', type: 'string'},
      StartDate:            {name: 'start_date', mapping: 'start', type: 'date', dateFormat: 'c'},
      EndDate:             {name: 'end_date', mapping: 'end', type: 'date', dateFormat: 'c'},
      EmployeeName:  {name: 'employee_name', mapping: 'employee_name', type: 'string' }
};
Ext.ensible.cal.EventRecord.reconfigure();
</pre><p>Notice that the <code>EventId</code> field has also been mapped here, this is the very barebones of what you can record in an <code>EventRecord</code> for it to work. The <code>EventId</code> must also match the <code>idProperty</code> of the <code>EventRecord</code> store. If you&#8217;ve used a proxy to handle all store operations then the <code>EventId</code> will be used to determine which CRUD operation to perform on the record.</p><div
id="attachment_37" class="wp-caption alignright" style="width: 218px"><a
href="http://jameshalsall.co.uk/wp-content/uploads/2011/06/Untitled.png"><img
class="size-full wp-image-37" title="Sample Event Body Template" src="http://jameshalsall.co.uk/wp-content/uploads/2011/06/Untitled.png" alt="" width="208" height="60" /></a><p
class="wp-caption-text">Sample of a Rendered Event Body containing Start Time and Title</p></div><p>The next objective is to override the renderer that specifies what our events look like in the calendar view. This is relatively straightforward to do once you know what method to override. Within each Calendar View we need to redefine our <code>getEventBodyMarkup()</code> function. The purpose of this method is to parse a template for the data in each of our events and return it. It uses place holders in the format of <code>{FieldName}</code> to inject the data for each event into the template body. For example, we could override the calendar&#8217;s <code>MonthView</code> event body template to cater for our custom mappings as follows&#8230;</p><pre class="brush: jscript; title: ; notranslate">
 // custom override for event renderer
Ext.override(Ext.ensible.cal.MonthView, {
      getEventBodyMarkup: function(){
          this.eventBodyMarkup =
                   '{description}' +
                   'Employee: {employee_name}';
          return this.eventBodyMarkup;
      }
});
</pre><p>Of course, using custom fields means that we would need to override or extend the default event editor window that is bundled with Ext Calendar Pro. I found that when doing away with most of the default fields its far better to create your own interface for editing the events. We can intercept the default behaviour by picking up on the <code>eventclick</code> and <code>dayclick</code> events in the <code>CalendarPanel</code>.</p><pre class="brush: jscript; title: ; notranslate">
listeners: {
      'eventclick' : function(view, rec, el){
            showEventEditWindow();
            return false;
      },
      'dayclick' : function(view, date, ad, el){
            showEventEditWindow();
            return false;
      }
}
</pre><p>Whilst this is a very quick and brief overview, the best way to learn more is to check out the examples <a
href="http://ext.ensible.com/deploy/dev/examples/">here</a> and read the <a
href="http://ext.ensible.com/deploy/dev/docs/">API documentation</a>. If you have any questions/suggestions, don&#8217;t hesitate to let me know.</p> ]]></content:encoded> <wfw:commentRss>http://jameshalsall.co.uk/custom-event-rendering-with-ext-calendar-pro/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> </channel> </rss>