Luke Morton
Web Explorer Extraordinaire
RSS

PHP 5.4 Alpha out!

Get it while it’s hot.

So I got back from watching Transformers 3 (pretty awesome) to find a message from the PHP-DEV mailing list:

Hello!

Stas has packed PHP 5.4.0alpha1 which you can find here:

   downloads.php.net/stas/

Please test it carefully, and report any bugs in the bug system, but
only if you have a short reproducable test case. Alpha 2 will be
released in about 2 weeks.

You can read more information about this release here:
www.php.net/archive/2011.php#id2011-06-28-1

regards,
Stas and David

Fecking sweeeeeeet! Most exciting feature so far from the change log? Traits for sure. Although ability to bind $this to closures is pretty handy too.

What are your favorite features from the log?

on 1st July 2011 at 12am as php 5.4 over excited much? Comments

This new theme

Not so sure about this theme now, damn I wish I had more designer juice in me sometimes… my passion just seems to be in logic however.

I’ll leave the passion to the pansies out there ha xxxx

on 21st June 2011 at 7pm as theme Comments

OOP FTW

It’s in the name, Object, Oriented, Programming. Generally in OO practices you lean towards describing your programs as objects. However its an easy to mistake the benefits of OOP when starting out.

I have seen many examples of programmers simply using classes to namespace their functions. I would certainly not call this pattern OOP. Take an example:

class SQL {

    protected $_query;

    public function conn()
    {
        return mysql_connect();
    }

    public function query($query)
    {
        return $this->_query = mysql_query($query, $this->conn());
    }

    public function getRows()
    {
        return mysql_fetch_assoc($this->_query);
    }
    
}

$query = new SQL;
$query->query('SELECT * FROM users');
var_dump($query->getRows());

What is actually represented as an object here? Perhaps an entire DB transaction? Maybe a query, but it doesn’t really, you can reuse the same object for multiple queries. I say this class lacks an identity.

OOP comes into it’s own when you realise you should be programming in objects, when you realise that most things can be described as objects and that objects should describe a single domain of logic. PDO as a database access layer does this fairly well. Here’s my own quick representation of a non-existent DAL:

class DB_Connection {}

class DB_Transaction {}

class DB_Query {}

class DB_Row_Collection {}

class DB_Row {}

You see what I mean? Each class can describe an individual object that you will need to manipulate in your program.

$connection = new DB_Connection;

// Create new transaction using established connection
$transaction = new DB_Transaction($connection);

// Add two queries to the transaction
$create_user = new DB_Query("INSERT INTO users (name) VALUES ('bob')");

// Update user count
$update_user_count = new DB_Query("UPDATE stats SET user_count = user_count +1");

// Add those queries to the transaction
$transaction->add_query($create_user);
$transaction->add_query($update_user_count);

// Do transaction
$transaction->commit();

Nice huh? And grabbing rows?

$select_users = new DB_Query("SELECT * FROM users");

// Execute query using this connection
$select_users->execute($connection);

// Get a row collection
foreach ($select_users->get_rows() as $_user)
{
    echo $_user->name."<br />";
}

Now that is what I call OOP. Sure this can be slightly long winded, but that’s when you can write static methods in a helper class to get what you want in a terse manner.

class DB {

	public static function connection_from_config(array $config = array())
	{
		$config += Config::load('database');
		return new DB_Connection($config);
	}

	public static function query($query, DB_connection $connection = NULL)
	{
		if ($connection === NULL)
		{
			$connection = self::connection_from_config();
		}
		
		return new DB_Query($query, $connection);
	}
	
	public static function query_result($query, DB_connection $connection = NULL)
	{
		$query = self::query($query, $connection);
		return $query->execute();
	}
	
}

Now with this helper you can remove a fair bit of bloat excess code when you do not need it!

OOP FTW.

on 25th May 2011 at 10pm as oop php Comments

The infinite version number

at 9pm as programming deployment Comments

Kohana’s Cascading File System for your Assets

Ever wanted to extend the benefits of Kohana’s Cascading File System to your assets? That is, allow your modules and application folders contain JS, CSS, images and other static content whilst at the same time being publicly accessible.

If you have then maybe Publicize is the Kohana module for you. With zero configuration all you need to do is clone it, drag it, or whatever, into the modules folder of your application! After doing so anything within a folder called “public” in your application and module folders will be publicly accessible, even content within sub directories!

Publicize is environment aware because depending on what Kohana::$environment is set to it will do different things. In fact whilst in production mode it does nothing at all for performance reasons, well saying that I would advise simply not including unneeded modules whilst in production.

During development your assets will be served via Controller_Publicize to ensure you always get the latest version of your file. This has an obvious performance price seeing as every asset load will be served via PHP.

During staging and testing each resource will be loaded once by Controller_Publicize whilst at the same time copying the file from your module or application folder into the requested location in your DOCROOT. If the folder structure requested does not exist it will be created with 777 permissions, you have been warned. From then on the file will be found within DOCROOT and served as static content.

You know the biggest problem I have with this module? I spelt it the American way whilst being British! I hope you enjoy it :)

on 24th May 2011 at 8pm as kohana module publicize Comments

www.infoq.com/presentations/Leaner-Programmer-Anarchy

Note to self: Watch this ASAP.

on 27th April 2011 at 9pm as programming anarchy Comments

Seriously if you’re not watching the Drizzle scene, you should be.

at 8pm as drizzle db Comments

Don’t give your customers what they ask for; give them what they want.

/via dhotson.tumblr.com/post/4195196001/ten-lessons-from-githubs-first-year

on 30th March 2011 at 9pm as github Comments

Object method chaining

Today I’ll start with some PHP and JS.

$('<div>A success message</div>')
	.insertAfter('h1')
	.delay(5000)
	.fadeOut()
	;
Image::factory('/my/path/to/image.jpg')
	->resize_proportional(1024)
	->flip('y')
	->save(function ($current_name)
	{
		return str_replace('.jpg', '-1024.jpg', $current_name);
	})
	;

So what’s all this about I hear you ask? Well it’s a cross language style that I use of Object method chaining. I do not know where I picked it up, I guess in bits and pieces along my journey to becoming me today.

A general rule of mine is:

  • Any public method that manipulates the object being represented by the current instance should return $this.
  • Get methods should never manipulate $this and usually return whatever you want to get or NULL in the case that what you want is not available.
  • Is, Has or other such boolean methods should return a boolean always.

Take an example of such a class:

class Sword {

	protected $_owner = NULL;

	protected $_sharpness = 'very';

	protected $_used = FALSE;

	public function set_owner(Owner $owner)
	{
		$this->_owner = $owner;
		return $this;
	}

	public function sharpen()
	{
		$this->_sharpness = 'very';
		return $this;
	}

	public function practice()
	{
		$this->_used = TRUE;
		$this->_sharpness = 'not very';
		return $this;
	}

	public function is_sharp()
	{
		return $this->_sharpness === 'very';
	}

	public function is_used()
	{
		return (boolean) $this->_used;
	}

	public function get_sharpness()
	{
		return $this->_sharpness;
	}

	public function get_owner()
	{
		return $this->_owner;
	}

	public function has_owner()
	{
		return (boolean) $this->_owner;
	}

}

This sword class is the perfect example of what I personally expect methods to return. Get should usually return something or NULL. Set should return $this and also set something. Is and has return a boolean, and everything else does something and returns $this. I think I just repeated myself, but it’s an important point and the premise of this post.

Why have such rules? Well going back to my first example, would you rather be stuck with this mess:

$image = new Image('/my/path/to/image.jpg');
$image->resize_proportional(1024);
$image->flip('y');
$image->save(function ($current_name)
{
	return str_replace('.jpg', '-1024.jpg', $current_name);
});

Keeping to simple rules of quality and DRY persuasion results in healthier code for both you and your co-developers.

One last thing, some of you may have noticed me dropping the semi-colons to the next line. I believe I picked this one up from shadowhand. The main impetus for this is to allow the expansion, contraction and commenting of individual method calls without forgetting, removing or commenting the semi-colon. For example:

$('<div>A success message</div>')
	.insertAfter('h1')
	//.delay(5000)
	//.fadeOut()
	;

So there you have it!

at 12am as quality dry php js Comments

My Model

Warning: This post started as a self rant. One of those rants that shouldn’t be directed outwards, only inwards. You know, one finger pointing forwards, three point back and all that? Well hopefully this should be someone tamer than it’s purer form.

A class should be written to describe an object. An object, one single entity. A class is a form waiting to be filled in. A class is not a half filled form, as an object is not a tray full of forms. A class may have methods that manipulate or persist these values, it may even store meta data, but it only knows about itself.

class Model_Todo_Item extends Model {

    public $text = NULL;

    public function save()
    {
        // Do SQL
        return $this;
    }

}

$todo_item = Model::factory('Todo_Item');
$todo_item->text = 'I must do the dishes';
$todo_item->save();

Above $todo_item represents one item, it does not describe a full todo list, we just want to describe an individual object, in this case, a list item. We can save this object. We can set $text. That is all. If you want to protect the modification of $text, you can do this with encapsulation:

class Model_Todo_Item extends Model {

    protected $_text = NULL;

    public function get_text()
    {
        return $this->_text;
    }

    public function set_text($text)
    {
        $this->_text = $text;
        return $this;
    }

    // ...

}

My model can get text, it can set text and it can save.

Model::factory('Todo_Item')
    ->set_text('Must conquer the world')
    ->save();

I didn’t even need to create a variable above, with chaining (returning $this) you can do things quickly and neatly.

Let’s try something else:

class Model_Todo_Item extends Model {

    protected $_text = NULL;

    public function __construct($id)
    {
        // Load from ID
    }

    // ...

}

My model can be constructed with an $id which loads from database using this as the primary key. Have a looksie:

Model::factory('Todo_Item', $id);
// Or
new Model_Todo_Item($id);

We can create helper methods too, these will likely be static because they just do some verbose stuff, they do not require initialisation of another object. Most importantly though, they do what they say on the tin:

class Model_Todo_Item extends Model {

    public static function create($text)
    {
        return Model::factory('Todo_Item')
            ->set_text($text)
            ->save();
    }

    // ...

}

My model has a handy method to create a new todo item:

Model_Todo_Item::create('Run home tonight');

That’s a handy shortcut!! How about some more shortcuts:

class Model_Todo_Item extends Model {

    public static function find_all()
    {
        // Do SQL and load into individual Model_Todo_Item's
        return array(/** Model_Todo_Item **/);
    }

    // ...

}

My Model can find all items and return an array of objects.

foreach (Model_Todo_Item::find_all() as $_item)
{
    echo $_item->get_text().'<br />';
}

So my Model can do a few things now. This is how Models should be conceived and perceived (in my opinion), at least domain models. Everything should just make sense. A model should not require something likes this:

$m = new My_Class_For_Something;
$m->find_by('field', 'value');
$m->do_my_find();

foreach ($m->get_list() as $_something)
{
    echo $_something['access_like_an_array'];
}

That could (and should) be like this:

foreach (My_Class_For_Something::find_by('field', 'value') as $_item)
{
    echo $_item->property;
}

Code should be written in small manageable chunks. Heavy work should be categorised and split up into logic domains, then placed in their appropriate models. Any logic to do with your Model, should be found in your Model.

To create an element you should not require a million methods especially non-chaining ones:

$m = new Something('Random string to describe something');
$user = new User;
$m->assign($user->id);
$m->more_info(array('key' => 'value'));
$m->save();

That could so easily be this:

$something = Something::create(array(
        'random' => 'value',
        'key'    => 'value',
        'more'   => 'value',
    ))
    ->assign(new User);

Have a bit of care for your work, put in a bit more logical though. It feels good to create quality, I tend to feel pretty shitty doing any less.

on 25th March 2011 at 7pm as PHP model Comments
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.