The most awesomest design pattern, ever to exist and that ever will exist!

At my current day job, someone came up with this design pattern and has implemented it in almost every class throughout the entire application, there are probably close to 100 implementations of this “pattern”. I had to post it because it’s just so awesome!

Firstly let’s late a look at the traditional factory method, it’s usually a static method that instantiates 1 or more objects and returns you the object.

class MyClass
{

    public static function factory($some, $params)
    {
        $it = create_some_object($some, $params);
        return $it;
    }

}

Simple and effective.

Behold! The tri-class factory method, 3 times more awesome than the normal factory method!

Firstly create your class as normal:

class MyClass
{
    ...code...
}

Then create a factory class, (you’re thinking, “what???”, but don’t think, just do):

class MyClassFactory
{
    public static $factory = null;
    ...static methods...
}

Note, some very important features, you must have the public static $factory variable, and it must be initialised to null, despite this being the default behaviour of PHP. The methods also follow a very important structure too, but we’ll get to this in a moment.

Finally, the 3rd and final class, the “Factory Impl” class:

class MyClassFactoryImpl
{
    ...non-static methods...
}

Then to put everything together we need to assign an instance of “Factory Impl” to the static $factory variable in the Factory class, this should be down outside of all the object structures, for added coolness:

MyClassFactory::$factory = new MyClassFactoryImpl;

Confused? You should be. But this is just the start of the awesomeness.

Next, you need to implement the factory methods, they should be implemented as normal public methods in the “Factory Impl” class, e.g.

public function getById($id)
{
    return new object($id);
}

For each method you create, you also need a static function to call this method in the factory class:

public static function getById($id)
{
    return self::$factory->getById($id)
}

Repeat for all your factory methods, and you’re done!

I would recommend that to make it as helpful as possible for other developers, make sure you put everything in one file and try and call the file something different from any of the class names you’ve used, this will ensure that they will probably have to use a require_once each time they use it as it’ll confuse most autoloaders.

You should end up with something like this:

class MyClass
{

    public function __construct($id = null) {}

    public function someMethod() {}

    public function someOtherMethod() {}

}

class MyClassFactoryImpl
{

    public function getEmpty()
    {
        return new MyClass;
    }

    public function getById($id)
    {
        return new MyClass($id);
    }

}

class MyClassFactory
{

    public static $factory = null;
   
    public static function getEmpty()
    {
        return self::$factory->getEmpty();
    }

    public static function getById($id)
    {
        return self::$factory->getById($id);
    }

}

MyClassFactory::$factory = new MyClassFactoryImpl;

There is no denying the awesomeness of this pattern, 3 times more objects, 3 times more memory, 3 times bigger stack, 10 times more code, god knows how many times more inefficient, but infinitely more fun! :D

Next week, stay tuned for the “super god” class!

Share

Migrating to MySQL 5.5 on Ubuntu

MySQL 5.5 has been GA since December 2010, however there are currently no deb packages available. Ubuntu takes all (or most of) it’s packages from the unstable Debian branch, hence the natural order of things is for Debian maintainers to do the leg work (e.g. creating the build scripts) and then Ubuntu can use this to build similar or newer minor versions for the Ubuntu OS. I suspect that as 5.5 is a major release and there are a considerable number of changes that the build scripts take a considerable amount of time to write and possibly some of the Debian modifications/patches need updates to ensure compatibility too, hence the long delay.

However, we can install MySQL 5.5 from the generic tarball and make a few “tweaks” to maintain the default Ubuntu structures and settings.

There are more straight forward ways to install MySQL, however the intention of this guide is to allow us to easily upgrade via multiple future available routes with minimal effort (e.g. via deb packages, or in their absence newer generic tar distributions).

1. Create user/group

Note: I manually chose system group ids looking at the latest system group id in /etc/passwd and /etc/group

groupadd -r -g 108 mysql
useradd -r -g mysql -u 106 mysql

2. Create folders

mkdir /var/lib/mysql
mkdir /var/log/mysql
mkdir /usr/lib/mysql
mkdir /usr/share/mysql
mkdir -p /etc/mysql/conf.d
mkdir /var/run/mysqld

3. Set a few folder permissions

chown mysql:adm /var/log/mysql
chmod 750 /var/log/mysql/
chmod g+s /var/log/mysql/
chown mysql:mysql /var/run/mysqld

4. Download the source and copy/move it to the default install folder in /usr/local. (This is not standard Ubuntu, however due to some of the compilation options on the tar package it avoids a few issues but maintains Ubuntu paths.)

wget http://www.mysql.com/get/Downloads/MySQL-5.5/mysql-5.5.8-linux2.6-x86_64.tar.gz/from/ftp://ftp.mirrorservice.org/sites/ftp.mysql.com/
tar xzf mysql-5.5.8-linux2.6-x86_64.tar.gz
mv mysql-5.5.8-linux2.6-x86_64 mysql
mv mysql /usr/local/

5. Move files to the Ubuntu locations and create simlinks “just in case” MySQL has something hard coded into the build that cannot be changed via the config.

cd /usr/local/mysql/
mv bin/* /usr/bin/
rmdir bin/
ln -s /usr/bin/
cp lib/libmysqlclient* /usr/lib
cp -r lib/plugin /usr/lib/mysql/
cp support-files/* /usr/share/mysql
cp -r share/* /usr/share/mysql
rm -r share
ln -s /usr/share/mysql share

6. Create the default data files and move them to /var/lib/mysql

scripts/mysql_install_db
cp -r data/* /var/lib/mysql
chown -R mysql:mysql /var/lib/mysql
chmod -R 700 /var/lib/mysql
rm -r data
ln -s /var/lib/mysql data

7. Copy the init script over to /etc/init.d and modify to suit our needs

cp support-files/mysql.server /etc/init.d/mysql

Edit with your favorite text editor and ensure the following are set:

basedir=/usr/local/mysql
datadir=/var/lib/mysql

8. Add my.cnf, the default 5.1 file will do, with 1 or 2 modifications. Specifically, check the basedir and datadir are set correctly, ensure Innodb is the default storage engine (as per 5.5) and note the new syntax for slow query logging (disabled by default). It would be advisable to set common Innodb options, e.g. pool size.

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket          = /var/run/mysqld/mysqld.sock
nice            = 0

[mysqld]
#
# * Basic Settings
#

#
# * IMPORTANT
#   If you make changes to these settings and your system uses apparmor, you may
#   also need to also adjust /etc/apparmor.d/usr.sbin.mysqld.
#

user            = mysql
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr/local/mysql
datadir         = /var/lib/mysql
tmpdir          = /tmp
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = 127.0.0.1
#
# * Fine Tuning
#
key_buffer              = 16M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit       = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1

log_error                = /var/log/mysql/error.log

# Here you can see queries with especially long duration
#slow-query-log
#slow-query-log-file     = /var/log/mysql/mysql-slow.log
#long_query_time         = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id              = 1
#log_bin                        = /var/log/mysql/mysql-bin.log
expire_logs_days        = 10
max_binlog_size         = 100M
#binlog_do_db           = include_database_name
#binlog_ignore_db       = include_database_name

#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
default_storage_engine  = InnoDB

#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem



[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition

[isamchk]
key_buffer              = 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

9. Start the server!

/etc/init.d/mysql start

If the server fails to start, check /var/log/mysql/error.log for clues.

Share