Technical

A DCI architecture implementation in PHP

For those unfamiliar with DCI, DCI stands for Data, Context and Interactions. It’s a way to fill the gap in OOP between what an object is and what an object does. It also gives use-case enactment first class status to improve the readability of the code. It was proposed by Trygve Reenskaug (the man behind MVC) and James O. Coplien.

Although DCI implementations have been done in other languages, it’s a bit lacking in PHP. I am only aware of two other implementations – the first is phpcore-dci, by Joe Chrzanowski. Although it does hit first on Google, I believe its implementation is a little backwards and far too restrictive. For example, it injects roles (and their interactions) into data objects rather than the other way around, ie. casting data objects into roles. It also requires a rather silly convention to follow which may not fit your style.

The second is by Jeremy Bush (lead developer of Kohana), as part of his Auto-Modeler-Demo project, which demonstrates quite a few technologies and practices. It’s definitely very good, and in fact has inspired this implementation, but I was not convinced in the casting technique used (via lambda functions).

Without further ado, here’s the implementation:

<?php
class Validation_Exception extends Exception {
    public $errors = array();
    public function __construct($errors) {
        parent::__construct('Multiple exceptions thrown.');
        $this->errors = $errors;
    }
    public function as_array() {
        return $this->errors;
    }
}

/**
 * A dumb data object for a person.
 */
class Person {
    public $name;
    public function __construct(Array $properties) {
        foreach ($properties as $property_name => $property_value) {
            $this->{'set_'. $property_name}($property_value);
        }
    }
    public function get_name() {
        return $this->name;
    }
    public function set_name($n) {
        $this->name = $n;
    }
}

/**
 * Interfaces allows us to specify what data objects can play this role.
 */
interface Actor_Requirements {
    public function get_name();
    public function set_name($n);
}

/**
 * The class that casts the data object as the role
 */
abstract class Cast_Actor extends Person implements Actor_Requirements {
    use Cast_Interactions;

    public function __construct(Person $p) {
        parent::__construct(get_object_vars($p));
    }
}


/**
 * What the role is able to do
 */
trait Cast_Interactions {
    public function link($roles) {
        foreach ($roles as $role_name => $role_instance) {
            $this->$role_name = $role_instance;
        }
    }
}

trait Romeo_Interactions {
    public function call_juliet() {
        echo $this->get_name(), ': Hey Juliet!', "\n";
        $this->juliet->reject_romeo();
    }

    public function leave() {
        echo $this->get_name(), ': Fine then. Goodbye.', "\n";
        //throw new Exception('The play ended unexpectedly.');
    }
}

trait Juliet_Interactions {
    public function reject_romeo() {
        echo $this->get_name(), ': Not now, sorry.', "\n";
        // Not really anything to do for validation, but just for demonstration
        //throw new Validation_Exception(array('Juliet isn\'t following her script.', 'Juliet rejected Romeo.'));
        $this->romeo->leave();
    }
}

/**
 * Inject role interactions into the casting to make our final roleplayer.
 * Separating the Cast_Foo object and the final roleplaying object allow for 
 * reusing generic casts.
 */
class Romeo extends Cast_Actor {
    use Romeo_Interactions;
}

class Juliet extends Cast_Actor {
    use Juliet_Interactions;
}

/*
// An example of how using traits can be useful
class Director extends Cast_Director {
    use Director_Interactions;
    use RomeoInteractions;
    use JulietInteractions;
}
 */

/**
 * Use case: enact Romeo & Juliet
 */
class Context {
    private $romeo;
    private $juliet;

    public function __construct(Person $p1, Person $p2) {
        // Cast objects into roles
        $this->romeo = new Romeo($p1);
        $this->juliet = new Juliet($p2);

        // Defines connections between roles.
        $this->romeo->link(array(
            'juliet' => $this->juliet
        ));
        $this->juliet->link(array(
            'romeo' => $this->romeo
        ));
    }

    public function execute() {
        try {
            $this->romeo->call_juliet();
        } catch (Validation_Exception $e) {
            $errors['validation'] = $e->as_array();
        } catch (Exception $e) {
            $errors['misc'] = $e->getMessage();
        }

        if (isset($errors)) {
            return array(
                'status' => 'failure',
                'errors' => $errors
            );
        } else {
            return array('status' => 'success');
        }
    }
}

$person1 = new Person(array('name' => 'Romeo'));
$person2 = new Person(array('name' => 'Juliet'));

$context = new Context($person1, $person2);
$result = $context->execute();
print_r($result);

Feel free to refactor this for your own architecture – this setup most definitely should not all be in one single file but should be split up as appropriate for autoloading, semantics or organisation.

I hope somebody finds this useful. It’s licensed under the IANAL license.

Life & much, much more

Game of Homes – upcoming Architecture Revue

Have you ever watched Game of Thrones? I haven’t, but that hasn’t stopped me or the rest of the folks from our faculty from creating this year’s annual Architecture Revue performance.

Game of Thrones - Architecture Revue

If you’re in Sydney and want to kill some time, come along and watch the show. If Australian university humour isn’t quite your thing, come along anyway to listen to the band.

Apparently it’s got knife-wielding priests, ghostly giraffes, and moose- but don’t take it from me, take it from yourself after you watch the show.

OK, enough blatant advertising, and apologies for the terrible pun.

For those interested, my main role is as musical director, though of course I do a bunch of Audio/Visual stuff too, and I shall post a bit more about that later.

Uncategorized

Architecture Portfolio Walkthrough, Year 1, Semester 1

A while back, I announced that holidays had started (well, now officially they have, just handed in my last assignment today) and that I was going back to all my projects and blogging more. The latter, obviously, was a complete failure, but hopefully this picture-filled post (all 20 of then, oh yes) will make up for the delay in the blog schedule (it was also a good opportunity to practice using the camera).

This is a walkthrough of my year 1, semester 1 architectural portfolio. There’s a lot of beginner-trash in it of course, but I hope I’ve condensed most of it from the around 150 pages worth of content. (Yes, you read that right – 150. That does seem excessive for a portfolio, but it actually isn’t that much, as they are double sided, and there were actually two portfolios, not one) So think of it as two 25 page portfolios really, plus extra content. Due to the immense quantity of work, I’ve cut out the majority and just focused on a few and will not have time to explain the details of each project.

The work inside was since March, so about 12 weeks worth of work, and the portfolio itself only had a week to create everything.

Note that for those who have been stalking me on WIPUP, some of this won’t be new stuff.

The portfolios were both presented in a stylishly hand-made briefcase. Yes, it is upside-down in the picture above. That briefcase was also the first proper physical object I’ve built before, so I”m quite pleased with how it turned out. An A3 sheet of paper fits very snugly inside.

Upon opening the briefcase, the audience is overwhelmed with tons of gewgaws and knick-knacks of every kind. For one of my courses, we were situated on the imaginary town of Cliffton (which has a landmark cliff, surprise surprise), upon which my building was a kayak manufacturing plant. The portfolio was designed as though a tourist had stumbled through the town and picked up trash along the way.

Looks exciting, eh? Well, let’s toss out the dodgily crafted kayak (needs lots of work) and the business cards with tiny sketches and drawings on them and look further.

The bulk of the portfolios were presented in two hand-bound hardcover books of cropped A3 and A4 sizes respectively. These held the parts which couldn’t be presented in more interesting formats. The A3 cover seems to have bent for some odd reason, perhaps its the glue.

The portfolio design itself was a very minimalist grid layout that some might remember first cropped up in my experimental web-folio user interface. Just smack in the center of the page. Pages were laid out in a “text” on the left, and “image-only” on the right per spread.

The left would always follow the same layout, and slowly build and construct an increasingly complex timeline of events as the person progressed further through the book. I found it a great way to put the work into perspective as well as to make the “text-only” section not so boring.

Some pages, however, with the more interesting technical drawings were complete spreads to-the-edge. The above we see a proposed abstract and conceptual transformation of the “CarriageWorks” site (a rather hip place here in Sydney, recently hosting TEDxSydney).

… as well as full-page renders, of course. People do like eyecandy.

… some of the more diagrammatic pages with thin strips through the page spread …

… and of course the napkin-sketches that show the birth of ideas.

More full-page renders – there is a lot of detail in these renders, which is why I chose the rather bulky pagesize of A3. (I find A3 landscape books rather cumbersome, but it was a necessary evil)

One of my projects involved the insertion of a set of rails and tracks into a back lane such that existing elements could be transformed and reattached into new layouts such that they performed different functions. (This wasn’t for the design course, but rather for the communications aspect, so let’s not look at why people would want to sit on bins and trip over tracks)

It was appropriate to create an IKEA-esque instruction manual (a separately provided A5 handbook) as to how to assemble the product, aptly named Konstruera Bagar. (name chosen by Erik Kylen) It means “Construct Arc”, I am told.

The insides are full of bad Swedish puns, unnecesary Swedish accents, and completely incorrect grammar, but let’s not get into that. It is, of course, also available in 80 different languages.

The design portfolio (the A4 book) favoured a more clean-cut “photos-only” showcase rather than the heavily diagrammatic approach of the communciations portfolio.

… here we see some of the detail in the tilework of the models done during design …

Along with the design book, a small fold-out visitors’ guide to Cliffton map was presented, offering both very scenic views and maps of the surrounding area and context, as well as a charming watercolour rendition of the building on the back – oh, and of course free coupons you can cut out.

My tutor was also invited to the monthly KayakersAnonymous pre-meeting congregation, showcasing the community areas of the building, and the various zonings that changed depending on the time of day.

Here we have the Kayak Maintenance Guide. It is probably important to mention that our imaginary town’s primary transportation system was kayaking through a system of canals. My building was essentially the town garage.

Apart from blabbering on about your warranty, the maintenance guide also details how to service your kayak, as well as exposes the internal processes of the buildings and various circulation paths you can take to minimize further damage to your kayak when coming to the building.

What briefcase would be complete without a newspaper clipping from the “Cliffton Times”, mischieviously dated Nov 11, 1918. It details the proposal of the building as well as the zoning decisions that were made within and outside the building site. It also pokes fun at some of my other group members – why not :)

Finally, two A1 panels of the final presentations from each subject.

Well, I hope that was interesting! I might post a PDF of the documents themselves, but that’s going to have to wait.

Uncategorized

Blender 3D: Architecture, Buildings and Scenery – Review

I recently received a book on Blender 3D architecture, Buildings and Scenery from the folks over at Packt Publishing. The author is Allan Brito, those who frequent BlenderNation might have heard his name a few times. I must say, it’s a good book, and I would have no trouble recommending it to folks interested in Blender. Here is my review on it:

Given the limited supply of Blender books available, I believe a book on Blender’s use in architecture is long overdue. Architecture is one of those industries where incorporating Blender into the workflow gives companies an advantage over others, yet the extent to which these advantages are recognised is, simply speaking, dismal. The book “Blender 3D: Architecture, Buildings and Scenery” has managed to address this issue and explain in a clear and concise way the advantages Blender provides, its limitations, and how to implement this tool into existing workflows. This focused approach allows the book to guide anyone, be it a novice or a trained expert, in the use of Blender.

One of the plus points of this book is that it doesn’t try to force the reader into using Blender for all tasks. Unlike other books which would try to promote an “ability to accomplish everything” relying on one program, this book recognises the areas in which Blender is limited, and guides the reader in the use of alternate tools which are more specialised in a certain field. Such examples include The GIMP, YAFRAY, and various script extensions to Blender. When introducing these external tools alongside Blender, the author chooses to focus only on relevant tasks instead of trying to document each feature of the application, which would be highly unnecessary and likely to be inadequate.

Another benefit is that the book explains how Blender is to be used, instead of letting users who are familiar with other 3D packages adjust on their own, since Blender’s interface and highly hot-key driven workflow are often seen as obstacles. This approach, also seen when introducing The GIMP as a tool (which has similar interface issues), gives the reader a firm foundation when using the tool, instead of later developing inefficient techniques when using the application.

Experience in using Blender is not a prerequisite for reading this book. Though the book doesn’t give a reader a lot of practice in modelling, it provides enough information to allow the reader to discover their own modelling style through experience. For those new to 3D graphics, this might be a hindrance, but for those who have used other packages, this would mean that the focus is solely on architecture, and hence a much more enjoyable read. Points are explained clearly and jargon is limited, though it enforces proper terminology when appropriate and covers architectural conventions which makes it easier to incorporate into existing workflows. Furthermore, the book’s focus is on architecture, but many of the techniques described can be applied to other uses, such as photorealistic rendering, modelling techniques, and animating processes.

The language used is informal, friendly and easy to follow, which encourages the reader to decide whether or not certain steps are appropriate for the job at hand, instead of instilling a “word is law” rule in the reader. Diagrams are clearly labelled, though beginners might find they will have to search for buttons and panels, as Blender’s interface is extremely customisable and prone to change in the future.

One demonstration of the books ability to communicate techniques well to the reader is how I was able to follow entire concepts introduced within the book without having to try them out on a computer. Other technically demanding books would normally require experimentation of tools and features before readers could be comfortable with a certain concept.

Unfortunately, the book is based on an older version of Blender. Blender, being open-source, develops all too rapidly, and changes – such as interface rearrangement – can confuse new users. One important example of this is when the book describes a UV editing mode to texture models, the mode of which is now non-existent – it was removed in a recent version of Blender.

Though the book does an excellent job of introducing Blender to architects, one aspect I believe it could expand upon is how Blender is going to progress in the future. Many people are concerned about using open-source applications, meaning that if the book could explain Blender’s rapid growth in popularity – potentially used as a representative for all major open-source applications – this could remove a lot of doubts companies might have.

Also, there were certain simple grammatical and spelling mistakes present within the text which detracted from the professional aspect of the book, which is extremely detrimental when trying to sell open-source software to commercial companies. Some of the formatting was not standardized, and the screenshots showed a lot of different interface layouts, which would confuse new users who are not familiar with Blender’s freedom when customising workspaces. These minor irritations aside, the book’s delivery of points is pretty good.

In conclusion, the book makes clear points, and delivers them in an easily understandable form for any audience. The use of chapter summaries helps the reader understand how each point has benefited them and which techniques should be used when. It takes into account current industry standards, and instead of fighting them, provides viable methods to collaborate with these standards, thus making it easy for readers to realistically apply knowledge they have gained from the book.

…and that’s it! I hope you found it useful, and I’m going to take a break for a few days. If you have any more questions about the book, feel free to drop a comment.