Zend Framework Application Patterns at DPC10

I’m currently in the fine city of Amsterdam enjoying what is incredibly my first PHP conference in ten years of developing with the language! Yesterday was tutorial day, with the full conference starting today, and I sat in Zend Framework Application Patterns by the informative and engaging Matthew Weier O’Phinney and Rob Allen.

The session was excellent, well worth attending, and dipped into many areas of ZF. Some of which I knew already, but there was certainly enough good tips on how to organise applications efficiently in ZF which I’ll be telling my team all about when I get back to the UK.

My notes from the tutorial day appear below, be warned they are rather long! You can also review the Zend Framework Workshop slides over at Slideshare.

Service layers

Think of the application as an onion layer. From the inside out:

Data Access objects (inner layer)

Data Mappers, Repositories, Transaction scripts

Domain Models and Entities (plain old PHP objects)

Service layer (outer layer: how will I interact with all this, the public API)

It’s better to have a rich domain model, validation in domain model.

Start with a plain old PHP object

Define schema based on objects you use

Create objects first

Create schema once models have been created and tested

Use mappers or transaction scripts to translate objects to data and back again.

Use Service Object to manipulate entities. Ie.

fetchEntry()

fetchComments()

addComment(), etc

What’s in a Service Layer?

Application specific logic

Forms, validation, caching

All the bits and pieces of the app I don’t want to deal with when writing the front-end.

Q: Should we use services for everything?
A: Use for all parts of an app, easy to test

Rob added:

he uses the form as the service layer

uses a mapper class based on ZendDbTable

compose the form in the service layer

tend to put search indexing on mapper layer (postSave method)

ACL

ACL is roles, resources and rights (resource privileges). By default ACL operates as a whitelist (i.e. open up privileges to those you trust). Blacklisting is less secure, not recommended.

One approach is to extend Zend_Acl and set up roles and resources in constructor. Roles are simply text strings. Resources are much the same but have an array of privileges that can also be passed (i.e. read, write).

Suggested logic:

Check ACL

Check the role acting on a resource has a right to perform the action

isAllowed() – checks role, resource, privilege

Matthew added:

I like to throw a specific exception for failed ACLs so I can detect it

I can then check for another exception case in the ErrorController to display a Not Authorised page (nice approach)