AddThis javascript error: addthis_efrom is not defined

Tuesday, May 19th, 2009

So all of a sudden, the AddThis button starts giving a mysterious javascript error on all of our CFS Website Service sites. It went from working perfectly to throwing an error, without any change to any of our code. When I would mouseover the AddThis button, firebug would display the following error: “addthis_efrom is not defined”. So I poked into the AddThis javascript code and found the particular line that was giving the problem:

s += efr("at_from",
          w.lang(al,8),
          _117,
          0,
          (addthis_do_ab||window.dbg?addthis_efrom:"")
         );

If firebug is telling me that addthis_efrom is not defined, then that must mean that window.dbg is defined. There are no other references to addthis_efrom and only one other similar reference to window.dbg in the AddThis code. I assume it’s something they use for debugging and then remove when they push their code live. There’s no definition for window.dbg anywhere in the AddThis code — that I can find. From the looks of the code and the fact that addthis_efrom variable isn’t defined, it appears that they’re no expecting window.dbg to be defined in the live environment.

I start looking through our javascript code — a convaluted pot that has had many fingers in it over the years — and find the culprit. A single line in one of our javascript files:

dbg = function() { return false; }

At some point, someone on our end created a function called dbg. Just so happens that at AddThis used that same variable name. Great. Tons of hassle and wasted time for such a trivial issue. I’m actually quite surprised that AddThis wouldn’t implement at least some manner of namespacing their variables, just to ensure that this kind of issue wouldn’t arise. Aside from maybe that variable name “debug”, I wouldn’t be surprised to find that a lot of people out there are using “dbg”. All that the developers at AddThis needed to do in order to avoid this hassle, would have been to either wrap their dbg variable in an object, to act as a pseudo-namespace, or even something as simple as prefacing their variables, something like: addthis_dbg or even at_dbg. Then again, maybe there is some reason that they chose to use dbg that I’m just unaware of. If nothing else, I’ll give them the benefit of the doubt…

I guess you could flip the coin and say that the onus is on us to namespace our own variables. That just doesn’t sit well with me. AddThis wants us to use their button, so they should be concerned with ensuring that their code won’t conflict with ours in anyway. No one is going to use a third party solution if it breaks their existing code base. At the end of the day, all of our debugging code that uses the dbg() function has to be changed in order to accomodate the AddThis button. Which isn’t much more than stress and hassle for us and our clients.

Zend Framework: Amazon S3 Component

Monday, May 11th, 2009

With the 1.8 release, the Zend Framework has pushed out a number of really awesome components. One that I got to work with recently, was Zend_Service_Amazon_S3. At the time that I started using the S3 component, it was still in the incubator. Since it has been released, the official documentation can be found here. Although the documentation is pretty thorough, there are a couple points-of-interest that I think are worth mentioning.

1. Global namespace. Amazon S3 is set up such that all accounts share the same namespace. So this means that if you create a bucket in your S3 account, that bucket name can’t already exist. I suggest picking a unique bucket name and then using that as a root “directory” for all your S3 files.

2. Sub-Buckets. In S3, there’s no way to create a bucket within a bucket. But there is an easy way to mimic that kind of functionality. All you have to do is name your objects as though they are part of a bucket path. E.g. if your bucket name is ‘offshoot’, and you’d like to create a sub-bucket called ‘uploads’ and put an object called ‘file.jpg’ in your ‘uploads’ bucket, you would just name your object ‘uploads/file.jpg’. The code would look something like this:

$s3 = new Zend_Service_Amazon_S3($myAwsKey, $myAwsSecret);
$s3->putObject(’offshoot/uploads/file.jpg’, ‘imagedata…’);

This will give the appearances of having a sub-bucket called ‘uploads’ within your root bucket. This should help you keep your objects nicely organized, as you would expect from any file system.

3. Pay attention to the ACL Headers. Amazon S3 has a pretty solid ACL for controlling who can do what with the files that you upload.

(Taken from the Zend Framework documentation):
S3_ACL_PRIVATE: Only the owner has access to the item.
S3_ACL_PUBLIC_READ: Anybody can read the object, but only owner can write. This is setting may be used to store publicly accessible content.
S3_ACL_PUBLIC_WRITE: Anybody can read or write the object. This policy is rarely useful.
S3_ACL_AUTH_READ: Only the owner has write access to the item, and other authenticated S3 users have read access. This is useful for sharing data between S3 accounts without exposing them to the public.

Make sure to use these to your advantage!

————————-

Overall, I’m really impressed with the quality of the components that ZF has been pushing out in the last little while. I’m looking forward to digging into the the Amazon EC2 component next!

Using PHP’s Imagick class to convert a CMYK jpeg to RGB

Friday, October 24th, 2008

We’ve recently converted all of our image processing from using GD to using ImageMagick and one of the biggest stumbling blocks in doing that has been the lack of documentation for PHP’s Imagick class. I ran into a problem when I realized that I needed to convert a jpeg from CMYK to RGB. After some googling, I was only able to find a solution that used imagemagick on the command line. This just isn’t a viable solution for my current needs, I need a solution in PHP, preferably using the Imagick class. Back to google. I finally find what appears to be exactly what I’m looking for, but it’s on one of those question/answer sites where you have to pay to see the answer. Forget that! So I read through the little Imagick documentation that exists and trial-and-errored my way to a working solution.

Here’s a simple script that gives a run through of converting a CMYK jpeg to RGB using ImageMagick’s Imagic class:

<?php

$filePath = '/path/to/your/file.jpg';
$i = new Imagick($filePath);

$cs = $i->getImageColorspace();

if ($cs == Imagick::COLORSPACE_CMYK) {

    print "Image is CMYK<br/>\n";

    ?>
    CMYK Image:<br/>
    <img src="<?=$filePath ?>"/>
    <br/><br/>
    <?php

    $i->setImageColorspace(Imagick::COLORSPACE_SRGB);
    $i->setImageFormat('jpeg');

    $cs = $i->getImageColorspace();

    if ($cs != Imagick::COLORSPACE_CMYK) {

        print "Image is no longer CMYK<br/>\n";

        // write it to a temp file
        $filePath = '/path/to/temp/file.jpg';
        $i->writeImage($filePath);

    }

} else {
    print "Image is not CMYK<br/>\n";
}

if ($cs == Imagick::COLORSPACE_SRGB ||
    $cs == Imagick::COLORSPACE_RGB){
    print "Image is RGB<br/>\n";
}

?>
RGB Image:<br/>
<img src="<?=$filePath ?>"/>
<?php

$i->clear();
$i->destroy();
$i = null;

Hopefully this will help some of you out! I know there are a lot of people out there looking for the same (or at least a similar) solution.

Javascript Controller

Tuesday, July 29th, 2008

Article Quicklinks

Wha?

What exactly do I mean when I say “javascript controller”? What I have in mind is a program/script that resides on the server side which controls the way the javascript is passed to the browser (or whoever requests it).

Let’s have a couple of examples to illustrate what I think a basic javascript controller should be able to do.

Consider the following HTML code example showing how to load two javascript files using only one <script> tag:

<html>
<head>
	<script type="text/javascript" src="scripts/script1+script2"></script>
</head>
<body>
	Hello!
</body>
</html>
Example1.html: Example showing two javascript files being included in the same script tag.

And consider the following javascript code example showing how to include/require another file:

/* REQUIRE: Coordinates */

var Circle = function()
{
	this.coords = new Coordinates();

	this.setCoords = function(x,y)
	{
	this.coords.set(x,y);
	}

	this.draw = function()
	{
		// ...
	}
}
Circle.js: Example showing a simple require statement.

And finally consider another javascript code example of a file loading another javascript file from some javascript code library.

/* REQUIRE: lib/Animation */

Animation.fadeOut('some_div_id');
FadeSomeDiv.js: Example showing a require statement from some predefined javascript library.

Why?

At the bare minimum, what I ultimately wanted was to have a script that would be able to require/include other files, especially from a reusable library or framework. But there are so many side benefits that come along with it.

  • the ability to (re)use a library or framework across all projects
  • less server calls (that is, the browser only grabs one big javascript file instead of a bunch of smaller ones)
  • organization (no more massive 100k files to work with)
  • sweet inheritance possibilities
  • future possible addons: caching; and compression, things like removing comments and whitespace, and maybe even variable name shortening

The point is that there are a ton of advantages in creating such a script – or, I suppose, in having someone else create one for you.

How?

So, if all of this sounds interesting enough to try out for yourself, let’s try get it setup.

You can download the controller, including the examples files, here:

Download Javascript Controller + Examples

Unzip that business to your server (or on your home xampp setup). Here’s a running example of example.html.

Included in the .zip are these files (a more thorough investigation of these files can be found in the next section):

example.html
The example html file showing how to include/require files.
scripts/.htaccess
This is a configuration file which tells Apache to route all requests from scripts/some/request/ to scripts/index.php (that is, route them to the javascript controller).
scripts/index.php
This is the controller. You can set the path to your own library in this file.
scripts/Examples/ShapesExample.js
This is the example javascript file that the example html file opens.
scripts/My Library/Shape/Circle.js
A circle object in the library.
scripts/My Library/Shape/Rectangle.js
A rectangle object in the library.
Contents of javascript-controller.zip

But there are a couple things to note about how the controller works:

  • The library path is set inside of the javascript controller (index.php); in the example case the library path is “My Library”. Just change the value of the $libdir variable to the path of your library, and you should be good.
  • The extension .js is always appended to the end of the requested script files, so just something to be aware of.
  • If a file is “required” twice, it will only be included once (the controller keeps track of the included files and checks for duplicates).
  • When a file is required (R), it will appear before the file that required it (A), but if another file (B) which appears before the first file (A) and which requires the same file (R), the required file (R) will always appear before both files which required it (A and B). (I get the feeling that could have been said much more simply..)

An explanation of what’s going on in the example included in the .zip

Alright, so if we take a look at this html file:

<html>
<head>
<script type="text/javascript" src="scripts/Examples/ShapesExample"></script>
</head>
<body>
	<input type="button" onclick="circle1.report()" value="Call method circle1.report()">
	<input type="button" onclick="rectangle1.report()" value="Call method rectangle1.report()">
</body>
</html>
	
example.html: showing off how to include files in the html file

We can see that the script is “scripts/Examples/Shapes”, but what’s actually going on is that there is a PHP script located at “scripts/index.php” which gets executed, and checks to see if there is a file on the system called “Examples/Shapes.js”.

Our example script “Examples/ShapesExample.js” looks like this:

/* REQUIRE: lib/Shape/Circle */
/* REQUIRE: lib/Shape/Rectangle */

var rectangle1 = new Rectangle();
rectangle1.setCoords(0,0,30,40);

var circle1 = new Circle();
circle1.setRadius(9);
circle1.setCoords(30,30);
Examples/ShapesExample.js: the shapes example includes the files circle and rectangle from the library

The Javascript controller reads in this file and parses it, looking for REQUIRE statements surrounded by comments, like the ones above. It then loads those files in the same way (reading and parsing), including more files.

The special case, like the one above (e.g. lib/Shape/Circle), is when something from the “lib” (the library) is specified. The library path is set inside of the javascript controller; in this example case the library path is “My Library”.

The javascript controller thus looks for the files My Library\Shape\Circle.js, which looks like this:

var Circle = function()
{
	this.x = 0;
	this.y = 0;
	this.radius = 0;

	this.setRadius = function(r) { this.radius = r; }
	this.setCoords = function(x,y) {
		this.x = x;
		this.y = y;
	}

	this.report = function()
	{
		alert("I am a Circle with a radius of " + this.radius + " and which sits at co-ordinates " + this.x + ", " + this.y + ".");
	}
}
My Library/Shape/Circle.js: a circle object, located in the library

And, it looks for My Library\Shape\Rectangle.js, which looks like this:

var Rectangle = function()
{
	this.x1 = 0;
	this.y1 = 0;
	this.x2 = 0;
	this.y2 = 0;

	this.setCoords = function(x1,y1,x2,y2) {
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
	}

	this.report = function()
	{
		alert("I am a Rectangle which sits at co-ordinates (" + this.x1 + ", " + this.y1 + ") are (" + this.x2 + ", " + this.y2 + ").");
	}
}
My Library/Shape/Rectangle.js: a rectangle object, located in the library

It then puts all the files together and spits out one big Javascript file, which looks like this:

var Circle = function()
{
	this.x = 0;
	this.y = 0;
	this.radius = 0;

	this.setRadius = function(r) { this.radius = r; }
	this.setCoords = function(x,y) {
		this.x = x;
		this.y = y;
	}

	this.report = function()
	{
		alert("I am a Circle with a radius of " + this.radius + " and which sits at co-ordinates " + this.x + ", " + this.y + ".");
	}
}
var Rectangle = function()
{
	this.x1 = 0;
	this.y1 = 0;
	this.x2 = 0;
	this.y2 = 0;

	this.setCoords = function(x1,y1,x2,y2) {
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
	}

	this.report = function()
	{
		alert("I am a Rectangle which sits at co-ordinates (" + this.x1 + ", " + this.y1 + ") are (" + this.x2 + ", " + this.y2 + ").");
	}
}

var rectangle1 = new Rectangle();
rectangle1.setCoords(0,0,30,40);

var circle1 = new Circle();
circle1.setRadius(9);
circle1.setCoords(30,30);
This is the generated javascript file that’s sent to the browser.

Hopefully there should be no surprises with that result.

And let me know what you think — it might be inspiring enough to write some of those future addons!

Zend Framework 1.6RC

Friday, July 25th, 2008

If you don’t frequent the zend framework website you might not have realized that they already have a release candidate for version 1.6 of the zend framework. What’s interesting about version 1.6 (other than the additions to my new friend Zend_Form) is that it comes bundled with the Dojo javascript framework. On the surface this seems like a good idea: a php framework and a rich integration with a javascript framework. Your basic all-in-one package. Looking deeper, I feel like this has the business equivalent to “code smell” to it. Why did Zend select Dojo out of all the javascript frameworks out there? The community doesn’t seem to think Dojo is the right way to go. All the blogs I’ve been reading seem to be really pushing jQuery. But then again programmers (yes, myself included) are a fickle sort and tend to always jump on whatever bandwagon seems to have the most hype. So now Zend has taken it upon themselves to make it easier for programmers already using the Zend Framework to start using Dojo. Did Dojo start loosing the popular vote and figure their best bet for the future is attempting to piggy back on the Zend Framework’s hype? The relationship between the Zend Framework and Dojo is clearly beneficial to both parties and the integration of the two will only become easier and more seemless over time. I suspect it will get to the point where the ease of using Dojo far out weighs the hassle at attempting to use another javascript framework. I figure the result can go one of two ways, developers using ZF will either: convert to using Dojo or come together and extend the Zend Framework to have a rich integration with other javascript frameworks.

In a perfect world, business wouldn’t determine the choice of programming language or tools that we use. As part of an open source community, we have the tools required to make our own decisions and to branch off when business begins to constrict our choices.

What do you think?

Free App: PHP Simple Gallery

Friday, July 25th, 2008

Here at the office, when we’ve run into a bottleneck design wise, we’ve used a collection of images to inspire us, mostly in the form of large, slow to open, and hard to share layered PSD resource files.

To fix this problem I slapped together this simple php image gallery. No database required, no extensive configuration. Just upload files and folders and you’re done.

The gallery seeks through up to 2 levels of folders and generates thumbnails* of png, jpg or gif images on the fly. The left hand navigation lists all the main folders and sub folders so you can get to what you need to look at quickly.

Installation is simple:
1. Un-Rar all the files.
2. Upload to your server
3. Create the directory ‘files’ in the same folder as index.php
4. Upload your files and folders to the ‘files directory’

thats it.

Feel free to give it a shot, modify it to your heart’s content. If you come up with a wicked awesome mod let me know and I’ll add it to any modifications that I do in the future.

Download Here

*Thumbnails are generated by WV4, modified by me to work with png, jpg and gif

Favour Composition over Inheritance

Wednesday, June 4th, 2008

I was just reading through the current issue of php|architect (April 2008) and I noticed a particular piece of code that irked me to the point that I need to write about it. If you’re interested, the article is Exceptional Error Handling. Don’t get me wrong, it’s a well written and informative article, however, one of the listings (Listing 9) has some really hacky code in it. The hack is only in the constructor, but the flaw is in the design. A flaw that can easily be overcome with a piece of sage advice from the Gang of Four: “Favour object composition over class inheritance” [GoF20]

The intention of the code is to have a singleton class that extends PHP’s ArrayObject class. Here’s the code snippet:

class LogService extends ArrayObject
{

    private static $instance;

    public function __construct(Array $loggers = array())
    {
        // examine backtrace to see how the constructor was called
        $backtrace = debug_backtrace();

        // throw exception if we were not called from the
        // getInstance() method of this class
        if ($backtrace[1]['class'] !- __CLASS__ ||
            $backtrace[1]['function'] != 'getInstance'){
            throw new SingletonException('...');
        }

        parent::__construct($loggers);
    }

    public function getInstance(Array $loggers = array())
    {
        if (!self::$instance){
            self::$instance = new LogService($loggers);
        }
        return self::$instance;
    }

    ...
}

NB: i left out the rest of the class and the content of
the exception message because it's not really relevant
to the point at hand.

Can you spot the problem here?

The problem is that this breaks one of the main rules of the singleton pattern — that new instance of the class cannot be created from outside of the class — and then attempts to reconcile it by checking the backtrace and throwing an exception. Since the constructor of the ArrayObject class is defined as public, any child classes of ArrayObject must also have their constructor defined as public. This is because access to a method of a child class cannot be more restrictive than that method in the parent class. The final solution ended up being a hacky mimic of the singleton pattern.

Ockham’s razor (or at least a paraphrased version): “the simplest solution is the best”

Checking the backtrace and throwing an exception is not the simplest solution. The simplest solution is to favour composition over inheritance.

Let’s look a little deeper at the ArrayObject class

ArrayObject

You’ll see that the ArrayObject implements 3 interfaces: IteratorAggregate, ArrayAccess, and Countable. These interfaces are what allow php to treat instances of the ArrayObject as native array, i.e. using it in a foreach loop, accessing elements of the ArrayObject, finding out how many elements are in the ArrayObject, etc.

Let’s see how we can use composition and interfaces to write an equivalent singleton class without the need for the hacky constructor


class LogService implements IteratorAggregate, ArrayAccess, Countable
{

    // the only available instance of this class
    private static $_instance;

    // an instance of ArrayObject. using composition rather than
    // inheritance
    private $_array;

    // private constructor as an optimal solution for the singleton
    // pattern
    private function __construct(Array $loggers = array())
    {
        $this->_array = new ArrayObject($loggers);
    }

    // method required by the IteratorAggregate interface
    public function getIterator()
    {
        return $this->_array->getIterator();
    }

    // method require by the ArrayAccess interface
    public function offsetExists($index)
    {
        return $this->_array->offsetExists($index);
    }

    // method require by the ArrayAccess interface
    public function offsetGet($index)
    {
        return $this->_array->offsetGet($index);
    }

    // method require by the ArrayAccess interface
    public function offsetSet($index, $newval)
    {
        return $this->_array->offsetSet($index, $newval);
    }

    // method require by the ArrayAccess interface
    public function offsetUnset($index)
    {
        return $this->_array->offsetUnset($index);
    }

    // method require by the Countable interface
    public function offsetCount()
    {
        return $this->_array->count();
    }

    public function getInstance(Array $loggers = array())
    {
        if (!self::$_instance){
            self::$_instance = new LogService($loggers);
        }
        return self::$_instance;
    }

    ....

}

In my opinion this is a much more elegant solution, even if it does require a little bit more coding (and very trivial code at that). There’s no way to call the constructor outside of the class and thus no need to manage the possibility of an exception thrown by the constructor. It serves the same purpose as the original code (you could even implement the php’s magic method __call() in the LogService class to essentially proxy method calls to the instance of the ArrayObject) and is more inline with the intention of the Singleton pattern.

What do you think? Which solution would you prefer? What do you think is more important: good design practices or less lines of code?

Oh CRUD… (Part 3)

Tuesday, May 6th, 2008

Well, somewhat unfortunately, there won’t be a part 3 to this blog post. I ended up pitching the idea to php|architect magazine (http://www.phparch.com) and they will be publishing it in their july 2008 issue. I’ll post any links and relevant data sometime in july. So keep your eyes peeled for that.

In the mean time, check out the current issue of php|architect here

Zend Framework Extensions

Tuesday, May 6th, 2008

Recently we made the decision to move from our custom php framework to the zend framework. With the recent 1.5 release, the zend framework has shown that it’s truly a force to be reckoned with. However, I quickly found that there were certain bits and pieces that I’ve become accustomed to using that weren’t (or at least weren’t readily) available within the framework. Here’s where the power of the zend framework comes in. I was easily able to extend the certain classes in order to incorporate elements of our old custom framework.

Over the next little while I’ll be creating some tutorials which will outline the various extensions to the zend framework that we’ve built.

Tutorial 1: Application Controller

Oh CRUD… (Part 2)

Monday, February 4th, 2008

My last post was basically just an outline of the CRUD processes and a brief touch on the design patterns that will allow us to make dealing with CRUD a thing of the past. If you weren’t already, hopefully by now you are familiar with various design patterns listed in my last post

Let’s start with a basic implementation of the Command Pattern:

Fig. 1A

Command

The Command class is an abstract class (or in this case, it could easily be an interface) that defines the methods which must be implemented by all subclasses. Note that it accepts a Context object as a parameter (I’ll talk more about the Context Object patter below).

Example 1A: A very simple Command class

abstract class Command
{

    /**
     *
     * @var Context
     */
    private $context;

    /**
     * Initializes the Command object. Ensures child classes cannot
     * change its interface
     *
     * @param Context $content
     */
    public final function __construct(Context $context)
    {
    	$this->context = $context;
    }

    /**
     * An abstract function to be implemented by subclasses
     * Processes the context object and returns a status result
     *
     * @return int
     */
    abstract public function execute();

}

Create

The Create class is a subclass of Command. In our simple case, it merely implements the execute() method. It uses the Retrieve class to get an instance of the Object (where Object is a class from your ORM. I’ll talk more about the ORM below) being created, performs operations on the object, and then marks it for insertion into the database. Example 1B is a very simplified version of the Create command, it is bereft of error checking and will require additional work before it is ready to be used; it’s just a snippet to get you started.

Example 1B: A very simple Create command

class Create extends Command
{

    /**
     * processes the context and instantiates, populates, and stores
     * a domain object
     *
     * @return int
     * @throws Exception
     */
    public function execute()
    {

        // get an instance of the object to be created
        $object = Retrieve::newInstance(
                          $this->context->getClassName()
                      );

        // delegate to the context to populate the object
        // with values from the request
        $this->context->populateObject($object);

        // mark the object for insertion into the database
        // note: alternatively, and depending on your ORM,
        //         insert into the database can happen here
        $object->registerNew();

        // put the new object into the context to allow
        // the caller of this method to get access to it
        $this->context->setObject($object);

        // return a status flag based on the execution
        // of this method
        return 1; 

    }

}

Retrieve

The Retrieve Command has the most functionality of the 4 CRUD Commands since it has static methods for returning object instances. In addition to it’s execute method, it has two static methods, newInstance() and findInstance(). The newInstance() method takes a class name as a parameter and uses the native php Reflection classes to return a new instance of the supplied class name. The findInstance() method attempts to use methods on the ORM class to retrieve an object from the database. If no object exists, it returns null, but could alternatively return an instance of the Special Case/Null Object Pattern. The execute method just uses the findInstance() method to attempt to retrieve an object from the database.

Example 1C: A very simple Retrieve command

class Retrieve extends Command
{

    /**
     * use information on the context to retrieve a domain
     * object from the database
     *
     * @return int
     * @throws Exception
     */
    public function execute()
    {

        // get an instance of the object
        // note: where 'find' is a method available on the
        //         ORM classes and used to get info from
        //         the database
        $object = Retrieve::findInstance(
                          $this->context->getClassName(),
                          $this->context->getId(),
                          'find'
                      );

        // mark the object a recieved from the database
        $object->registerClear();

        // put the new object into the context to allow
        // the caller of this method to get access to it
        $this->context->setObject($object);

        // return a status flag based on the execution
        // of this method
        return 1; 

    }

    /**
     * returns an instance of the object that is represented by
     * the supplied class name and unique identifier.
     *
     * @param string $className
     * @param mixed $id
     * @return Object
     * @throws Exception
     */
    public static function findInstance($className,
                                        $id,
                                        $methodName
                                       )
    {
        $method = new ReflectionMethod($className, $methodName);
        $object = $method->invoke(null, $id);
        return $object;
    }

    /**
     * Returns a new instance of the supplied class name
     *
     * @param string $className
     * @return Object
     * @throws Exception
     */
    public static function newInstance($className)
    {
        $class = new ReflectionClass($className);

        if (!$class->isInstantiable()){
            throw new Exception(
                'Class in context object is not instantiable.'
               );
        }

        $object = $class->newInstance();

        if (is_null($object)) {
            throw new Exception('No instance of an object given.');
        }

        return $object;

    }

}

Update

The Update Command is very similar to the Create command. Instead of retrieving a new instance, it attempts to retrieve an instance from the database. It delegates to the context object to update the object properties with values from the database and marks it for update in the database. Based on the code for Create and Retrieve, you should be able to figure out the code required for the Update Command.

Delete

The Delete Command is not unlike the Update command. It retrieves an instance of an object from the database and marks it for deletion. Again, based on the code above, you should be able to figure out the code required for the Delete Command.

Until Next Time…

In my next article, we’ll delve into the Conext Object and ORM classes, tying up all of the loose ends and finishing with a complete CRUD solution.