ZF2 ServiceManager Custom ViewHelpers

The previous article explains how the ‘Zend\Mvc\Service\ModuleManagerFactory‘ sets initializers that gather information from certain keys in the configuration. A ‘ViewHelperManager’ is configured to read the ‘view_helpers’ key. Which expects regular ServiceConfiguration config.

We have seen that the Mvc  ‘ServiceListenerFactory‘ maps the default ‘ViewHelperManager’ to ‘Zend\Mvc\Service\ViewHelperManagerFactory‘. This class does not only have a default helper map, which includes a HelperConfig that will add a factory under the ‘navigation’ key, but also extends from ‘Zend\View\HelperPluginManager‘, which in turn contains the configuration for more ViewHelpers.

And it doesn’t stop there.

Continue reading »

ZF2 Skeleton Application with Ctrl\DomainService

After creating the domain models and updating the database accordingly, we need to create a ‘Ctrl\DomainModelService‘, for each entity, to manage it. This will allow for the models themselves to be unaware of their persistence.

ctrllib provides a DomainServiceLoader comparable to the ControllerLoader. It is configured through the ServiceManager, and thus gives us many options in return:

  • uses module configuration and can therefore override other module DomainServices
  • it ensures correct initialization of your DomainServices
  • DomainServices can be fetched from wherever you have a ServiceLocator
  • instances can be aliased or marked as shared
  • possibility to add custom initializers or even to override the whole factory

Going further with the Car and Company models created in the previous post, we are going to create a ‘DomainModelService’ for both of them.
To create a DomainService we need 2 things: a class, and a configuration key pointing to the class.

Continue reading »

ZF2 Skeleton Application with Doctrine and ctrllib

Building further upon the previous post, I’m gonna follow up with some more integration into ZF2. I’ve been building this class library as a ZF2 module. since it is only a class library, it does not contain any MVC elements. So to be able to work with it I’ve also copied the ZendSkeletonApplication, and added a couple of tools.

  • Composer : dependency management
  • Doctrine 2: ORM Layer (and database managerment via cli)
  • Phing: build scripting and database management
  • DbDeploy: database migration
  • ctrllib: my extensions library for ZF2 and Doctrine 2
  • ctrlAuth: a module based on ctrllib provinding MVC for authentication and authorization
  • Twitter Bootstrap: view helpers and layout

To install the SkeletonApplication just clone the github repo, and fire the ‘composer.phar install’ command.

for more setup options, follow the installation guide in the README file in the repo.
The application provides a default database setup you can manage with phing.

After installation, your application should look like this.

app landing page

ctrlSkeleton

Continue reading »

ZF2 ServiceManager configuration walkthrough

ZF2 is all about extensibility, and the new ServiceManager and Config make it very easy, if you know how. Extensibility comes with some complexity, and it may be a bit harder to try and trace where everything is going, especially when using events.

With the ZF2 Configuration manager and Service Locator configurations, it’s not always as simple to know where to find the defaults, and how to best override them. This post might remind you of the factoryfactoryfactoryfactory post from joelonsoftware

I wanted to implement some custom navigation stuff and soon began to wonder how the config works, and how I can manipulate it to inject my custom view helpers or navigation pages. This post will cover the buildup of the service manager, and I plan to do some follow up posts to go into some of the main service factories.

Continue reading »

Custom default templates in ZF2

My previous post explains how I’ve set up my module structure, for the modules I create under my ‘Ctrl\Module\’ namespace. That post shows you how to configure the autoloader correctly, so the module classes can be accessed. This post will explain how I configured the view manager to avoid template name collisions that this system could cause.

The problems start when a controller in the Auth module does not return a ViewModel with a template specified. the ZF2 MVC registeres a couple of eventListeners to inject a ViewModel if one was not returned, or inject a template based on the matched module/controller/action pair if a ViewModel was returned, but does not have a template set.

For example the action ‘Ctrl\Module\Auth\Controller\IndexController::indexAction()’ that resides in the Auth module will be injected with the template ‘ctrl/index/index’

As you can see it only uses the root namespace of the module to generate a template name. This may seem fine at first, but what if I add a second module that uses MVC? lets say, a blog module:

The action ‘Ctrl\Module\Blog\Controller\IndexController::indexAction()’ that resides in the Blog module would also be injected with the template ‘ctrl/index/index’

Continue reading »

Zend Framework 2 modules with subnamespaces

Zend framework 2 has a new module approach that lets you set things up almost any way you would like. When I create code for myself, I always use the same root namespace ‘Ctrl’. and I want to keep it that way.
For a small testproject I currently have 3 modules of my own:

  • The first one is the application module which will house the MVC application and its classes, its root namespace is ‘AppName’ and it resides in the ./module/AppName directory
  • The second one is a class library module, its root namespace is ‘Ctrl’ and it resides in the ./vendor/ctrl-f5/ctrllib directory
  • The third one is an Auth module, which also contains its own mvc application and classes, the root namespace is ‘Ctrl\Modules\Auth’ and it resides in the ./vendor/ctrl-f5/auth directory

ZF2 allows modules to have any namespace you want, as long as you configure the autoloader correctly, when using subnamespaces you should specify the correct path in the module listener config. This means it should go look for classes in the ‘Ctrl\Modules\Auth’ namespace in the Auth module first, before falling back to the ‘Ctrl’ module.

Continue reading »

Domain layer and ZendFramework2 using Zend\ServiceManager

UPDATE: ctrllib has been implemented in CtrlSkeleton, providing easy database management for Doctrine entities and implemented ViewHelpers for Twitter Bootstrap.

In the previous article I gave a brief overview of how the current implementation of my Domain Layer looks. To be able to use these classes inside ZF2 controllers I used a custom ServiceManager Factory. This custom ServiceManager will take care of Dependency Injection and register configured DomainServices

Continue reading »

Domain Layer with Doctrine2

UPDATE: ctrllib has been implemented in CtrlSkeleton, providing easy database management for Doctrine entities and implemented ViewHelpers for Twitter Bootstrap.

In a previous post I explained briefly why you need a Service Layer, since then a lot of things have changed, so here’s an update of how I handle things at the moment.

For starters I’m going to stop calling it a service layer and use the term Domain Layer, which is more adequate:

  • my implementation provides a base DomainModel and provides additional domain model related classes (e.g.: Form)
  • concerning service classes are related to the domain model
  • ZF2 adds its own ServiceManager so in the ZF2 world, a Service is something much broader

I’ve been working on a new implementation which can be found on my github: ctrl-f5/ctrllib. please check the github repo for a complete and up-to-date implementation.

This article gives a brief overview of how the base Domain related classes look, integration in ZF2 will follow.

Continue reading »

GoDaddy and SOPA: I’m moving [UPDATE: Done!]

There has been a lot of fuzz the last weeks about GoDaddy supporting SOPA.

Not only are they supporting the bill, resitricting a free and open internet, they are also releasing false statements to try and calm down customers by saying they dropped support. On the day of this writing however they have not dropped their support officially.

No matter wether they will drop their support, i’m already looking too move my 5 domains plus hosting away from the company. If an internet company does not get how bad such a bill can, and will, be from the second they lay their eyes on it, they do not deserve any of my money.

I must say i have never had problems with their services or anything, but supporting SOPA is really a statement of complete idiocy, in which i will not partake. This is a completely selfish act on the behalf of GoDaddy imo, so they will loose me, among many others as a customer in the weeks to come…

If you too are a customer, please inform yourself about SOPA.

Note to Self

ubuntu php dev prep commands:
sudo apt-add-repository ppa:dominik-stadler/subversion-1.7
sudo apt-get update
sudo apt-get install vim php5 apache2 libapache2-mod-php5 mysql-server phpmyadmin imagemagick subversion git
sudo apt-get install php-pear php5-xdebug php5-sqlite php5-curl php5-svn php5-mcrypt php5-ldap php5-imagick phpunit
sudo a2enmod rewrite
echo 'ServerName localhost' | sudo tee /etc/apache2/httpd.conf
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
sudo service apache2 restart

pear prep commands:
sudo pear upgrade
sudo pear channel-discover pear.phpunit.de
sudo pear channel-discover pear.symfony-project.com
sudo pear channel-discover components.ez.no
sudo pear install phpunit/PHPUnit --alldeps

mounting shared folder in virtualbox:
sudo mkdir /mnt/workspace
sudo chmod 777 -R /mnt/workspace
echo '[FOLDERNAME]  /mnt/workspace  vboxsf  defaults,rw 0   0' | sudo tee /etc/fstab
sudo mount -a

install sun java jdk to run PHPStorm
sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
sudo apt-get update
sudo apt-get install sun-java6-jdk

(thx to this blog for the tip on the repo)

install openVPN support in gnome
sudo apt-get install network-manager-openvpn-gnome

Zend Framework ContextSwitch

Today was the day I got tired of constantly disabling the layout and viewRenderer when making ajax calls in the ZF project I’m currently working on.
Today is the day I went and visited my old friend, the Zend Framework ContextSwitch Action Helper.

Continue reading »

Building PHP with bundeled GD on Ubuntu

I was having trouble with some GD library functions not working in my PHP5.3 install on Ubuntu. Apparently Debian distributions do not compile PHP with the bundeled GD library, since it is a branch of the original GD, they consider it insecure.
To fix this problem I downloaded the sources and compiled PHP with the correct GD library.

Continue reading »

Closures in PHP5.4 alpha

The PHP community has been on a roll lately, after the great new release of PHP5.3 last year, a shiny new alpha is seeing light aka PHP5.4. The featurelist is not as big as the one of the previous release. But that’s because the previous one was huge… sporting stuff like namespaces, anonymous functions and late static binding.
PHP5.4 is mostly aimed at improving the previous release, but also gives us devs some nice features to enhance our codebase.

Continue reading »

Debian based Linux flash plugin

Lot’s of websites are still using Flash to play movies. I personally think this is counter productive because of it’s pour compatibility, and support not beeing native. It’s biggest competitor at the moment is HTML5. It can do video playback natively in the browser, with hardware acceleration and better power management. HTML5 also does not exclude a large userbase of iOS internetters.

Continue reading »

Upgrading GoDaddy to 4th Generation Hosting (4GH)

Godaddy recently “upgraded” their hosting capabilities. As they call it: 4GH. Now this is probably all just marketing tricks, especially because they still do not support PHP5.3 officially on shared hosting… (workaround here (not tested yet))

They also publicise the fact that there are EU servers now, but I’m not sure if that’s actually a new thing… anyway, I wanted to make sure I was in on the goodness.
A one sentence google got me there right away, the server is upgrading for free as I’m typing.
go get yours here, your hosting will be upgraded within the 72 hours.

PHP Library

This is the entry page for the Ctrl library

Service Layer and Zend Framework part2

info: for my new implementation with ZF2 and Doctrine2 please check here

Since my last post, I’ve had some time to reflect on my take on a ServiceLayer and do a little experimentation. This time it around it won’t be all talk and no action though, time to get your code-writing-mittens on. For the purpose of this post I have created a GitHub repository, as the series will progress (if it ever will of course) I should end up with a descent, flexible, robust implementation.
A few points are to be made clear before we get our hands dirty. I will only be using stable libraries, so no ZF2 for now, I’ll be sticking to ZF1.11. (Although Matthew Weier O’Phinney wrote a nice introduction about the new plugin broker architecture in ZF2 which will come in handy in situations like this…). Luckily the autoloader rewrite in ZF 1.10 will allow us to use PHP 5.3 namespaces in our library classes. Another new PHP feature that will come in handy will be Late Static Binding.

Continue reading »

PHPUnit and floating point precision

Last week I’ve had some trouble unit testing a function that converted a point on a map given in degrees, minutes and seconds, to a longitude and a latitude. I did not write the function myself, but was only unit testing it. PHPUnit gave me some weird output, from which I could not extract a cause. Some mighty debugging got me to the bottom of it.

Continue reading »

Service Layer in PHP

I’ve been thinking about robust, extensible, and easy patterns or strategies for setting up an application. Starting from an MVC viewpoint, I feel there’s a need for an extra layer, a service layer.
The service layer can handle workflow that only represents business logic. This meas the Controllers and Models can focus on their own tasks, being handling request logic and persistence logic respectively.
Service layer is a broad concept, and there are many ideas and examples available, for different languages and frameworks. My goal is to try and sculpt it in such a way that it fits in with PHP and Zend Framework.

Continue reading »

Xdebug, Zend Server CE and Widows 7

Trying to get Xdebug working to enable PHPUnit’s code coverage ability. Here’s how I got it working:

Download the Xdebug dll from http://www.xdebug.org/download.php, you can find the information about which compiler was used and wether thread safety was enabled in phpinfo().
In theory you could place this dll anywhere on your system, since you’re installing it as a zend_extension, you are obligated to provide the full path. Albeit it is probably best to put it somewhere in the Zend Server installation directory. I myself put it in the default, which you can probably find at the end of your php.ini file, under the [Zend] section, in the extension_dir directive. But even if you put it in that directory, you will still have to give it the full path later on. The extension dir only refers to regular extensions, not zend_extensions.

For configuring the setup I recommend going through the ini files themselves, as the ZendServer’s webinterface gave me some problems, as to setting the directives in the php.ini to extension instead of zend_extension.

Add the following to the bottom of the [Zend] section in the php.ini, with the correct path ofcource:

zend_extension="C:\Path\to\Zend\ZendServer\lib\phpext\php_xdebug-2.1.0-5.3-vc9-nts.dll"

In order for this to work correctly we need to disable the Zend Debugger and Optimizer (for some reason…). Go to Zend\ZendServer\etc\cfg\debugger.ini and delete the following line:

zend_extension_manager.dir.debugger="C:\path\to\Zend\ZendServer\lib\debugger"

in the optimizerplus.ini file, in the same dir, delete and change the following lines:

; delete or comment this one
zend_extension_manager.dir.optimizerplus="C:\path\to\Zend\ZendServer\lib\optimizerplus"
; change this one's value to 0
zend_optimizerplus.enable=0

Restart apache (or just php will do) and check you phpinfo() if it has an xdebug section.

Google Font API and Directory

Nobody knows why but Google has always been good for developers. They give things to us, we would never expect from a large corporation, at least not for free. Just look at the javascript tools they released, or Google Analytics. Recently I found something that will again ease the pain of webdeveloping: Google Font API and Directory.

A new website design arriving in your mailbox is always a stressfull moment. Will it be complex, or will it have features you’ll strugle with cross-browser wise. Designers also tend to use pretty fonts, instead of widely available fonts, who do look good, but are a pain to implement in a cross browser way. This is where Google comes in with a helping hand.

The API allows you to load font from Google’s font directory, as well as other providers. First thought on this aren’t too positive, the fonts all seem a bit pixilated, and they doesn’t look very high quality when viewing the demo texts. That aside, they have made it very easy to implement them, all you need to do to laod a font from Google font directory is add a link tag.

<head>
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
    <style>
        body {
            font-family: 'Tangerine', serif;
            font-size: 48px;
        }
    </style>
</head>

What the link does is send a request for a stylesheet to google, which in turn renders a stylesheet for the specific browser doing the request. And it’s as ready as it’ll ever be.
More information can be found here

ASP MVC2 typesafe generic listbox renderer

I was putting together my first listbox in asp.net mvc2, and found that it would be quite tedious doing this a lot. Beeing a programmer, and thus lazy, I started thinking about a solution for this. Here’s what I came up with.

Continue reading »

jQuery Event Propagating

For a website I helped building at work I had to make some tabs hanging from to top of the browser viewport. When the mouse hovered over any of these tabs, a content pane slides down. I’ve created a plugin to do this which I’ll maybe write up and post some time. For now I’m going to walk through some of the problems I encountered with event propagation.

The whole contruction is pretty standard: a container div containing all content panels, which are hidden and displayed at appropriet times. followed by an ul for the tabs. These are at the bottom for obvious reasons. To let the panel slide down I used the mouseover() function on the li elements of the tabs. To hide the panel again I used the mouseout() function on the container div, this ensures that the panel does not close when moving the mouse to different tabs or over the content of the selected tab. This is where it went wrong, when moving from tab to tab or our of the tabs into the content panel, the panel closed. After some fiddling and debugging I found our that the .mouseout() event comming from the tab elements propagated to the surrounding container, triggering it’s .mouseout() and thus closing the panel.

Now istead of digging into the API and documentation I stubournly searched for any workaround or fixes, without success I might add. I tried stopping the event manually, and setting event target parameters, but nothing seemed to solve the problem. When the frustration took the upper hand I posted my problem on stackvoerflow.com, and the answer came within minutes (!). The problem lies withing the function I chose, as the jQuery documentation appearently clearly states.

This is the last paragraph of the documentation:

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.

So all I had to do was replace the .mouseout() with .mouseleave() and all problems solved.

Release guessing

Google AndroidA while ago I bought myself a new phone. I was fed up with Windows Mobile, but that’s a whole story by itself… So my new phone ran Google’s Android 2.1, with the added joys of HTC’s sence smeered over the original UI. The latter is a nice addition by the way, I quite like it. The problem however is the following: about 2 months after my purchase Google released Android 2.2 A.K.A. Froyo. This brings some nice features aswell as claiming a 400% speed improvement.

This update is available for the Google Nexus One, but not yet for my HTC Desire. This is the case with all software updates due to the fact that HTC needs to tinker with their sence UI and various applications to update them to the new platform aswell. As soon as word from Google got out, HTC owners all around the interwebs started specualting about when HTC will update their phones. Beeing a customer myself this actually annoys me quite a bit. I’ve payed well enough for this device, and I have to looking about on the interwebs for rumours about speculated release dates. Why doesn’t HTC want to provide us any information on this? Surely they have got to have an idea themselves? I can’t imagine they don’t have any planning internally…

There are a few drawbacks on making release plans public, especially when you aren’t going to be able to stick to it, but I think you’re frustrating many more customers by just letting them stand into a corner wondering… People are going to set dates for themselves anyways, which could be wild guesses or leaks from trusted sources, but they do want dates set. So why not come clean and make your release plans public? I think it will only benefit the customer relationship.

CakePHP localized form validation

I’ve noticed a lot of techniques to handle localized form valaidation messages. Some even require hacking core Cake classes. Lots of people are still wondering on how to set it up as easy as possible. And still the answers available in the cookbook are allthough correct, not the best or smartest way to implement this. Some time ago I came across a nice way how to get this working. The only thing you need to do is overwrite a model function.

Assuming that L10n is properly set up.

When a field does not pass a validation rule, the following function is called.

Model::invalidate($field, $value = true);

This message takes as a first parameter the model field which didn’t pass validation, and the error message as $value. The only thing to do is thus translate that message, this can easily be done by overwriting the method. notice the function __().

//in your AppModel
function invalidate($field, $value = true)
{
    return parent::invalidate($field, __($value, true));
}

Now that our function is properly setup you can easily change the error messages for the fields in your models.

var $validate = array(
    'username' => array(
        'rule' => 'isUnique',
        'message' => 'FIELD_UNIQUE'
    )
);

In your .po file you can then add a msgid "FIELD_UNIQUE" and it is translated automaticly by the L10n class.