ZF2 Form Collection Templates

Hey everybody, been a long time! Today I’m coming to you with a topic that has bugged me for quite some time and I am still surprised that I can’t find a single blog about this. I’m talking about ZF2 form collections with templates. The current documentation has a very nice articles on how to work with Zend\Form\Element\Collection and granted in most cases this is absolutely sufficient.

When writing big backend-applications however I was never happy with the default rendering of forms. And while you’re able to do many things with the default markup, in other times that’s simply no longer an option. Furthermore working with deeply nested collections isn’t all that easy.

With this blogpost I’ll be presenting to you the solution that I came up with so far. It is by no means ideal or perfect but I can work with it just fine and I am hoping that some of you guys will find this useful as well, so here we go!
Read More…

Learning PHP

Hey everyone,

this time I’m coming to you with a bit of a meta-topic that’s been going through my mind lately. And that’s “Learning PHP”. In this post I’ll guide you through my findings of ~15 years ago and will then compare this to the process of newcomers to the business who are about to learn PHP just now. And you’ll notice that there is a huge difference between the times. A difference that I deem to be not good at all. So let’s kick it off
Read More…

Using Zend\Stdlib\Hydrator for JOIN-Queries

Last week I stumbled upon the need to join two tables together. A need that probably almost everyone out there has on a more or less daily basis. In my case however this was outside the scope of any ORM like Doctrine2 or PropelORM. It was while writing a plugin for WordPress and adding an ORM on top of that would have been way too much overhead, so we decided it would be best to simply use the SQL connectivity provided by WordPress and use some Zend-Components on their own. In this Blogpost I will demonstrate how to use Zend\Stdlib\Hydrator when working with JOIN-Queries.

The use-case

The use-case is pretty simple to understand. We have a Clients-Table and an adjacent Addresses-Table. To start of simple a client will have exactly one address. We won’t be using any key-table in between so our DB structure looks like the following:

database relationship between clients and addresses for hydrator example

Database Relationship between Clients and Addresses

For those who want to try it, either manually create a table structure like displayed above or use the one I created with the following sql-statement:

 Joining the Tables

With the database set up what we want to do is get a single user and it’s address. Both Client and Address should ideally be their respective objects. First off, let’s start by writing the query that will net us the result we want. Let’s write a query to get the result for the first client:

So let’s quickly create a script that will execute the above query. Since it’s pretty similar to my use-case I will go with the default PDO implementation by PHP.

The result will be a very simple array that contains all the information that we have requested.

As you all may know though, it’s not really that much fun to be working with arrays. It’s been preached so often that you need Objects, their respective Interfaces, yadda, yadda and all that stuff. Not going into the pro-con debates now but I do believe that objects are almost always to be preferred to be working with.

Objects and preferred result

Since we’ve got the query working so far, let’s create the models that we want to use. Both Objects are pretty standard with the Client  Entity also containing the Address  entity.

In the following Client model you’ll notice that we have a  $address property which is declared to be of type  Zf2demo\Entity\Address . In addition to that the setter- and getter functions for this property will also only accept and return the  Address -Entity.

With those models set up, we’re now able to declare what kind of output we do want. So here goes, we want this (slightly modified without property visibility):

 Zend\Stdlib\Hydrator to the rescue

Most people have probably played around with the hydrator-component at some point in time. The likeliest one to come across is probably the  ClassMethods -hydrator that uses keys to populate an object using the objects setter functions. We’re going to start our hydration process by using exactly the said hydrator:

As you can see we have a Client  object as we want, sadly though the Address  object isn’t populated.

And this is only normal. The $result  that we’re passing into the ClassMethods  Hydrator does not contain a key called 'address' . So how do we do this? The answer is: we have to use a different Hydrator. To be precise, we need to use the AggregateHydrator  which in turn uses multiple other Hydrators. Let’s go through this step by step. First off we’re implementing the AggregateHydrator and queue up the ClassMethods Hydrator to get the same result that we do have right now.

Executing the code above will change literally nothing as far as the output is concerned. So how do we get the Address hydrated as well now? The answer is surprisingly simpel: write a Hydrator for it. Basically the logic is this:

  • We have an array with several addr_  properties that reflect our Address  entity
  • We need to hydrate those properties into the Address  entity
  • We then need to put the Address  entity into the Client  entity using the setAddress()  function

Let’s first queue up the hydrator that we’re going to write. Let’s call it AddressHydrator .

Now that we have queued up the hydrator we need to implement it. We’ll be extending the ClassMethods  hydrator as our baseline to ease up our life a little bit. Then we have to iterate over all results to filter out only the parts that belong to the Address . And after that all that remains is to set the Address  onto the Client  entity. Ultimately you’d end up with something like this. Please see the code-comments for detailed description of what is happening:

With this set up we will now be able to properly hydrate our result into nested Objects.

The result

Here’s the full code example with the query that will turn into a beautifully hydrated Client and Address object.

The result is simple beautiful!


When I ran into the problem of having to do manual hydration over multiple tables (it’s much more complex inside my application) I didn’t know about the AggregateHydrator  yet. However working with it was surprisingly intuitive. And while this Blogpost is really long the actual amount of work that needs to be done is fairly simple. If you take a closer look at the custom AddressHydrator you’ll notice that many parts of this hydrator can be abstracted. And that’s precisely what I did. However showing this is outside of the scope of this post and will follow up sometime next week.

One thing that’s missing here as well is the extraction of the Client object. While the Client data is extracted into a beautiful array form the part of the Address still remains an object. That’s something you can easily fix, however once again, this is a bit out of the scope for one blogpost. Stay tuned for updates on this matter, it will follow in the near future.

Also let me know what you think about this feature of ZF2. Did you ever run into the need for this? Did you find the solution within the documentation? Or did you fall back to using a full ORM anyways?

Useful Links:

Dependent Select Lists in ZF2

Hey everybody, one need many people have is to make <select>-Lists dependent on each other. No matter what website you’re running, chances are that you use <select>-lists that depend on each other as well. While this is mainly an aspect of proper usage of JavaScript, many people don’t know how to prepare their HTML Elements using ZF2 in a way that they are able to properly being used by their JS-Libraries. This blog-post demonstrates how to achieve this goal.

Different Strategies

There are two common ways to make select lists dependent on each other. The first one would be to make an AJAX-Request against your web-server whenever someone selects an entry within the first list. This request would then return JSON-Data that contains the information for the second, depending, list to populate. You would choose this option when the full range of values for the second list is very large. Since – in my experience – lists are rarely as large as that, we will not cover this option in this blog-post. However rest assured that after reading this blog-post you’ll have all the knowledge you need to make this strategy happen, should you require it.

The other option would be to populate the second list with all possible data that can be selected. You would then simply hide all elements (using JavaScript) that are incompatible with the selection of the first select list. This approach is very handy, very fast and easy to follow. So let’s get it started!

All the magic you need to know

First off we’re going to create a Form that contains two select lists with some dependent data. As you will see shortly, the example will be very simple to follow as we’re mainly just grouping numbers within respective ranges.

As you can see we’re hard-coding some values here that are tightly grouped together. We have three different ranges of numbers (00-09, 10-19, 20-29) as well as all numbers from zero to twenty-nine in the second list. The magic happening here that many people don’t know about is the assignment of the value_options. Most people only know about value_options like this:

However there is a much more powerful way to do this. In essence those value_options are all elements that will be rendered as an <option> element. And as such it is able to hold attributes as well. Therefore, instead of providing an array of key=>value pairs, we’re providing an array of array-elements. Each element defining a single rendered option-element. For example:

In the above example we assign value options in the more complex way. Each element has a value and a label like usual. The relation is as simple as key=>value equals value=>label. However as an addition we also add some attributes to each element that contains our wanted data-attribute (data-key). And with this information the rest is simply some small piece of JavaScript to get the front-end working.

Working the front-end

As mentioned previously, most of the work for dependent select lists is done by JavaScript. Here is how you would do it using the provided backend-sample:

What’s happening here is pretty simple. To start out we have two select lists that contain many option-elements. All of those elements are visible. Now whenever someone selects anything from the first list, we then are going to hide all elements on the second list. We re-enable the first element of the second list, which basically is the empty_option and furthermore we enable all elements of the second list where the data-key matches the one selected within the first list. And that’s really all there is to it.

Security Considerations

Now with all beautiful front-end stuff there usually come some security implications. For example what happens if the user has turned off JavaScript? Of course you could make your website absolutely REQUIRE JavaScript but – even today – that’s not the best thing to do. The advantage of this approach here is that the form does work without JavaScript enabled.

However inside our database it would be weird to have an entry for the range “00-09″ with the value “22”. Therefore on the PHP Side of things, or rather within ZF2, we have to find a way to also validate our select list combination. In my experience this is best done using the Zend\Validator\Callback . Here is how you would use the validator in a simplified way:

As pointed out within the comment block, there’s no way you would hard-code such validation. Any real-life-scenario will always have a database check of the given combination. Doing this is as simple but the additional dependencies for the form would make this quick tutorial overly complex.

The most interesting aspect of the callback validator is the use of the $context which is basically a reference to the whole form. Using this you’re able to access all element-values from the form and therefore you’re able to validate the selected value against some haystack.

Working Repository

I’ll always welcome any questions or feedback regarding this matter. If you’d like to see a full working example, I have set one up on my GitHub account for you guys to check out.
manuakasam/tutorial-dependent-select-lists @ GitHub

Refactoring Bad Code using ZF2 – AbstractOptions

Hey everyone, it’s been a very long time since I’ve last been able to write something for you. Sorry about that! Today I’ll be talking to you about something that has come up lately. I’ve been working on a big project with a lot of people. We had an API-kinda class that handles soap Requests between an internal and an external Server. This class required many different URLs. Those URLs additionally had to be different for several staging setups. This quickly became very messy and I decided to refactor the configuration aspect of that class using the AbstractOptions class from Zend\Stdlib . Let me show you an example of said service class:

In this example we have a Service-Class that requires an instance of SomeService as well as three string parameters that represent several URLs the service will call from separate functions. Now I’ve mentioned that several staging setups required different configurations, so for example we have this setup:

I suppose you get the idea. This was the case for all URLs. Now with just three parameters like that it wouldn’t be too bad. We had 15 once I joined the project. By now we’re above 20… And worse of all, with many people working on one class over GIT we actually had troubles keeping up the correct order of things. It was a simple mistake to make to switch up two variables in the middle of the constructor. You know, adding each new variable to the end of the constructor is far too mainstream :D

Anyways, we came to the conclusion that this setup is horrible, so what can you do? The answer is as simple as the final implementation. You use an Object that stores all these configuration parameters and you simply inject that Object into the class wherever you need this. ZF2 provides us with a very nice base-class that we can use: AbstractOptions

Build your Options class

The first thing to refactor this messy setup was to create the options class. For the sake of simplicity I will stick to just the three configuration parameters that I’ve used in the example above.

The next thing in line would be to properly set-up your configuration. Setting up the config files properly will not only make the implementation of the AbstractOptions much easier, it will also increase the read-ability of your code by a lot. Let’s look at my example:

As you can see we have set up an config array with the top level namespace of our module. Inside that sub-array are key-value-pairs set up with the key being underscore-separated value names. We do this so that AbstractOptions will have an easy time to match the config-keys to our WebServiceOptions protected properties.

Now we need to find a way to bring those config values into our object. We do this by using a Factory-Class for our WebServiceOptions. Create it like this:

With this set up the configuration array passed into the WebServiceOptions class will be read from the AbstractOptions base-class which in turn will set the protected properties based on the configuration array. It’s magic, good magic!

Now let’s refactor the Service class and finish the configuration of the factories:

We also need to modify the factory class for this Service:

Let’s quickly take a look at the configuration for the factories as well:

Using the AbstractOptions

With all of this set up you’ll now be able to use the configuration you need within your Service-class. Just to mention this, this kind of OptionsClass can be used anywhere you need configuration. It is not restricted solely to services. But let’s see how we will use the config:

And just like this we have cleaned up the class and have a super useful options class that we cna inject anywhere we need this configuration. One thing however isn’t very optimal yet. It may happen that no proper configuration is provided. You have two ways to make sure there’s always config available. The first one would be to make sure that default values are always provided within your modules module.config.php, this is what we have done in this example here.

The other way would be to set the default values inside the Options class itself. This is the approach that personally I do prefer. You’d do it as simple as this:

And that’s it. Whenever you have new options available, all you need to do is write a new protected property within the Options class, add setter and getter functions for it and you’re done. No more messing around with constructors is required. When UnitTesting the class, you won’t ever have to inject 20+ configuration options into the class just to get the test working.

Even if this may not have been the only problems with said class, this little change already improved the life of everyone working with the class. We have improved the consistency of our configuration and cleaned up the constructor of this one class. And all that took was 10 Minutes of time which in the future will safe us hours. And could have saved many hours if we would have done so from the start.

Anyways, I hope that you’ll be able to make use of this information in the future and I promise to be writing a little bit more in the near future again! Until then, take care everyone, happy coding!

Setting up a development-environment on Windows

Ever since I posted my first installation tutorial for Zend Framework 2 a lot of things have changed. Composer has become much more awesome and PHP 5.4s internal webserver has become widely known. Due to all these changes I’ve wanted to do a video tutorial for quite a while now which finally I managed to do. Please leave me lots of feedback so I can improve for future video guites.

ZF3 Status Update Hangout #1 – Wrap Up

The first Hangout from the Roave team is done and the guys have given some great insight into the thoughts behind Zend Framework 3 (ZF3). In case you missed the talk – or if you just want to get a quick overview about what has been talked about – you’re at the right place. I am going to wrap up the whole talk and try to sum it up in a few lines what the keynotes have been.
Read More…

Understanding Zend Framework 3 … before it’s out!

Hey guys! Everyone knows how important it is to understand the concepts of a framework to truly use it at it’s best. With Zend Framework 2 (ZF2) a lot of people coming from Zend Framework 1 (ZF1) were shocked at first. So many new concepts, so many new buzzwords and more importantly what’s the need behind all those. ZF2 was a big step forward and by now a lot of people have gotten accustomed to the way ZF2 works and why it does so.

While ZF2 is a great Framework there are still a couple of things that are just not ideal. A little example would be that a lot of people use $this->getServiceLocator() inside their Controllers. While this is OK, it’s actually considered bad practice. The way things are looking right now, this feature will be removed in Zend Framework 3 (ZF3) to basically force people to use proper dependency injection using the ServiceManager.

And that’s what this post is all about actually. ZF3 is not close around the corner. It’s still many, many months ahead. But there are reasons why you should bother and get information about ZF3 as soon as possible. If you understand why changes are introduced – and most of them are explained, some will be explained at a later point i guess – then you can spot errors in todays code already! You can improve your current code by knowing what’s going to be “in” a couple of months away.

Zend Framework 3 on Google Moderator

One way to follow the development is to keep track of the discussions for Zend Framework 3 Ideas on Google Moderator. Not only will you be able to keep track and understand coming changes, you can actually do something against it! Does something sound just not right to you? Counter-Argument and downvote! ZF3 as much as ZF2 is a Community-Project and if the absolute majority of the community is against a change, chances are quite high that a change won’t happen.

ZF3 Tagged Issues on GitHub + Wiki

Probably the most technical information you can get is available right inside the ZF2-Repository over at GitHub. All Issues / PRs with the Tag ZF3 are about the very topic of introducing or debate about changes happening within the development of Zend Framework 3. This would be the ideal place for you to get involved with the actual ZF3-Development.

Aside from the issues on GitHub, there’s also a Wiki-Entry which lists a lot of the changes in a little more comprehensive format. More specifically, it lists up all the bc-breaks that are happening, so wisely read those! Thanks to Bakura for pointing that out.

Google Hangouts for Zend Framework 3

This actually is the core of this Blogpost. Just today i learned about a great Project that some of the great minds behind Zend Framework started. Marco <Ocramius> Pivetta, Evan <EvanDotPro> Coury and Ben <DaspriD> Scholzen will be holding a regular series of Live-Videos / Hangouts where the will be talking about the current status of development of ZF3. They will be highlighting some of the core changes and give reasons for why they are doing so. In addition to that you will be able to ask live-questions via chat at #zftalk.dev @freenode.net

I can only suggest to you guys to follow at least those hangouts. This will be roughly an hour worth of your time to understand Zend Framework 3 before it’s even out!

Follow the Hangouts here: Zend Framework 3 Status Hangouts. The first one will be held at November 6th at 15:00 UTC. Mark you calendars guys!

Understanding ZF2 Configuration

In Zend Framework 2 we no longer have the commanding application.ini, instead we got the option to configure our website or rather the modules on a per-module-basis. Furthermore, the modules are able to overwrite each others configuration. With this in mind, it makes it even more important to understand how ZF2 manages the configuration files of several modules internally. In this blog i will guide you guys through the internal process of the framework.
Read More…

Zend\Form\Element\Select and Database Values

One of the most common questions currently is how one is able to populate a Zend\Form\Element\Select with data from the database. In this blog I am going to demonstrate to you guys how you can achieve this using three different ways. First will be the very barebone way using Zend\Db\Adapter\AdapterInterface, another way will be using the Zend\Db\TableGateway\TableGatewayInterface and the third option to make this possible using a Doctrine\Common\Persistence\ObjectManager.
Read More…

1 2 3  Scroll to top