Setting the umask when using Capistrano

16th April 2013

This is one of those posts to remind me how I solved a problem last time!

I've recently been using Capistrano for deployment and other remote tasks and it's proving quite useful.

One problem I ran into was that the umask was being set to 022 when using Capistrano and 002 when I was ssh'd into the server itself.

After a bit of research, I discovered that the secret is to put the umask statement in my .bashrc file before the line that says [ -z "$PS1" ] && return as when Capistrano logs into the server, it doesn't have an interactive shell (and so $PS1 isn't set.

My .bashrc now looks like this:

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
 
umask 002
export PATH=~/bin:$PATH
 
# If not running interactively, don't do anything
[ -z "$PS1" ] && return

(This is on Ubuntu 12.04 LTS)

Minding my own business

3rd April 2013

After nearly ten fantastic years at Big Room Internet, I have decided to take the jump and run my own business! Having concentrated on project management for the last year or so, I am happy to return to hands-on development. I also intend to provide training and consultancy services.

I'm really excited by this new phase of my career. I have created a shiny new company for interesting projects: Nineteen Feet Limited. If you want to hire me, then please get in touch.

Over the years, I've discovered that I most enjoy developing directly for a client and building solutions that meet their specific needs. I've had great success teaching at conferences (such as PHPNW and ZendCon) and am looking forward to providing bespoke Zend Framework training to developers.

Objects in the model layer: Part 2

1st April 2013

I previously talked about the terms I use for objects in the model layer and now it's time to put some code on those bones. Note that,as always, all code here is example code and not production-ready.

An entity

My entities are plain old PHP objects:

namespace Book;
 
class Entity
{
    protected $id;
    protected $author;
    protected $title;
    protected $isbn;
 
    public function __construct($data = array())
    {
        $this->populate($data);
    }
 
    // Data transfer methods
 
    public function populate($data)
    {
        if (array_key_exists('id', $data)) {
            $this->setId($data['id']);
        }
        // repeat for other properties
    }
 
    public function getArrayCopy()
    {
        return array(
            'id'     => $this->getId(),
            // repeat for other properties
        );
    }
 
    // Entity-specific methods
 
    public function isValidIsbn()
    {
        // validate ISBN and return true/false
    }
 
    // Property getters and setters
 
    public function getId()
    {
        return $this->id;
    }
 
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }
 
    // Repeat for other properties...
 
}

There's nothing particularly complicated here. We have an object with a number of properties and some methods. This object represents a book, so we have properties of author, title and isbn. We need to be able to set and retrieve the properties so there is a get and set method for each one (only getId() and setId() are in the code snippet above to save space!)

Generally, I populate an entity from a mapper and use a pair of methods to do this: populate() and getArrayCopy(). These methods transfer the data in the properties to and from an array.

There are also entity-specific methods within the entity. For this object, I have a method called isValidIsbn(); for a user object, I may have a method called getFullName() which concatenates the user's first name and surname.

A mapper

The mapper knows how to load and save entities. This is a hand-rolled one:

namespace Book;
 
use PDO;
use Book\Entity;
 
class Mapper
{
    protected $pdo;
 
    public function __construct($dsn, $username, $password)
    {
        $this->pdo = new PDO($dsn, $username,  $password);
    }
 
    public function loadById($id)
    {
        $sql = 'SELECT * FROM book WHERE id = :id';
 
        $statement = $this->pdo->prepare($sql);
        $statement->setFetchMode(PDO::FETCH_ASSOC);  
        $statement->execute(array('id' => $id));
 
        $result = $statement->fetch();
        if ($result) {
            $book = new Entity($result);
            return $book;
        }
 
        return false;
    }
 
    public function fetchAll($order)
    {
        // Select all books from database using PDO
        // iterate over each one and create a Book\Entity object
    }
 
    public function save(Entity $book)
    {
        $data = $book->getArrayCopy();
        if ($data['id'] > 0) {
            // Update data in table using PDO and set $result
        } else {
            // Insert data into table using PDO and set $result
        }
 
        return $result;
    }
 
    public function delete($id)
    {
        // Delete row in table using PDO
    }
}

In the mapper, I have methods that load with multiple entities and also ones that work on a single one. I like to use the method prefix "find" for methods that will return an array of entities and "load" for methods that return a single entity. This is just a stylistic thing, but I find it makes reading code easier. We then have save and delete methods that allow us to save and remove an entity from the data store.

This is just a skeleton of a specifically written mapper that users PDO. In a ZF2 application I use ZfcBase\Mapper\AbstractDbMapper and in other applications I tend to abstract the common code into a base class and extend.

Service objects

Lastly, service objects provide the API to the rest of the application:

namespace Book;
 
use Book\Mapper;
 
class Service
{
    protected $mapper;
 
    public function __construct(Mapper $mapper)
    {
        $this->mapper = $mapper;
    }
 
    public function fetchAllByTitle()
    {
        $results = $this->events->trigger(__FUNCTION__.'.pre', $this, array(), 
            function ($result) {
                return is_array($result);
            }
        );
        if ($results->stopped()) { 
            return $results->last(); 
        }
 
        $books = $this->mapper->fetchAll('title');
 
        $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, 
            array('books' => $books));
 
        return $books;
    }
 
    public function loadById($id)
    {
        $results = $this->events->trigger(__FUNCTION__.'.pre', $this, 
            array('id' => $id), 
            function ($result) {
                return ($result instanceof Book\Entity);
            }
        );
        if ($results->stopped()) { 
            return $results->last(); 
        }
 
        $book = $this->mapper->loadById($id);
 
        $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('book' => $book));
 
        return $book;
    }
 
    // etc
}

A simple service object essentially proxies through to the mapper. I generally have more specific methods, such as fetchAllByTitle(), but that's a personal preference. In this example, I have an ZF2 event manager in play and the service object triggers events as required.

The service object is also useful when there are multiple related objects. For instance, if books had tags that were loaded separately, then I would have a method such as loadTagsIntoBook($book) on this service object. Of course, others prefer to use an ORM, such as Doctrine for these things.

Summary

This overview shows the type of methods that I have in each type of core object in my model layer. My controllers and view helpers only ever deal with service objects and entities, so I can change my mapper at any time.

You also need to think carefully where the business logic lives. I'm a fan of putting the logic in the entities as well as in service objects. Others tend to like their entities to be quite "dumb", though.

Ideas of March: It's my content and my opinion

28th March 2013

If there's one thing Twitter is not good at, it's holding a discussion on something controversial. Sean Coates noted this problem when he said: "I’m not worried about having my opinion disagreed with; I *am* concerned that I will be crucified for something I don’t mean." I suspect this is because you don't have the space to develop an idea on Twitter. It also doesn't help that Twitter is a conversation which means that people are arguing before you've written your second tweet!

As Chris Shiflett wrote earlier this month, real writing happens on blogs. With a blog you have the space to write down what you mean and develop the idea. However, even here there is risk. Lorna Mitchell noted that comments make it easy to criticise. You can leave an quick "drive-by" insult anonymously for minimal effort. This can become a disincentive to write opinion pieces on blogs too.

Like Chris, I also strongly believe in owning my data. My blog provides information that I want to share and more important, information that I want to find again! I was caught out on my Automatic Apache vhosts post where I linked to an alternative solution which has subsequently been taken down. Information that I want to refer to again must be on my blog as otherwise I can't be sure it'll be there when I need it.

I will continue to share technical things on this site as I believe that my posts are useful to others. Over time, I intend to blog more opinionated pieces. My views on some topics should be shared and would be a useful reference to point people at. Sometimes, I will turn off comments and encourage others to respond by writing their on their own blog. In more than 140 characters and less anonymously.

Objects in the model layer

22nd March 2013

I currently use a very simple set of core objects within my model layer: entities, mappers and service objects.

Entities are objects that represent something in my business logic. For example, in my traditional Album's tutorial, the entity would be the object that holds one album. It has properties such as title, artist and date created and methods that are specific to this entity.

Mappers know how to save and load an entity from the data store. This could be a database or a web service or an CSV file on disk. There is no requirement that a given entity maps to a single database table (or file on disk) as the mapper can simply use multiple tables for different properties within the entity if it wants to. The entity has no knowledge of how it is loaded and saved. This isolation means that I can have multiple mappers for the same entity that store it to different data stores.

Service objects provide the API that the rest of the application uses. I allow controllers and view helpers to talk to service objects, though I appreciate that others have a different take on MVC. Any given service object knows about mappers and entities and anything else that the business logic requires. I like having a service object as I can rework which mappers do what without having to touch the rest of the application. The service layer also know about other app details such as sending emails after a form is submitted. In an event based system, such as a ZF2, these details can now live in their own objects which listen for events triggered by the service object.

I dislike the phrase "service object" as the word "service" means so many things to so many people. I haven't heard a better phrase yet that everyone understands though.