Exploring the MVC

During the last weeks while I have read some documents about the model view controller pattern (MVC), which seem to be wrong in my eyes or better expressed, which mix and merge different application layers in a wrong way, I decided to write this blog post. Everybody who reads this text should know for what the shortcut MVC stands. It describes the responsibilities and dependencies between model, view and logic in the top level layer of an application. As I understand it, this means all parts in the presentation layer and nothing else. But most documents wrote about business logic, when the topic controller is treated, and this assertion is wrong in my opinion. Business logic and business models aren't part of the presentation layer, they build a further layer in an application. Keeping each layer independent, means that the presentation should know as few as possible about the underlying business logic.

Because practice is more understandable than all written text, I would like to explain my thoughts with a little example. The following diagram shows a simple business modell for a product catalog which implements a transaction based product storing. Beside the business classes you can find all possible exceptions in this diagram.

![ ](simple business model)

The class mpProduct provides the context model in this example, a simple object which only consist of the product name. mpProductCatalog is some sort of list object that is wrapped around the underlying storage as it occurs in most applications. The mpProductTransaction class can be used to encapsulate a product modification until it is persistent stored in the mpProductCatalog- instance. Finally you see some exception classes that could be thrown during a normal product process. The complete source code can be found here.

To insert a new mpProduct-object into the mpProductCatalog we have to create MVC infrastructure, which means a controller and a view.

At this point I will ignore the details and the whole environment around these two components and I will concentrate onto the method doAddProduct() which tries to add a new product to the mpProductCatalog-instance. The source code for the view and the controller from the following diagram can be found here and here.

![ ](simple controller view diagram)

Now let's take a look at the required logic for an insert operation. What must be done? First we have to get an instance of mpProductCatalog, then we have to create a new mpProduct object and we have to open a new transaction for this object. Then we can try to insert the new product whereby we have to take care about thrown business model exceptions. The listing below shows the required code for the doAddProduct() method.

<?php
    public function doAddProduct()
    {
        $name = $this->view->getText();

        // Create a new product
        $product = new mpProduct( $name );

        // Get the product catalog
        $catalog = mpProductCatalog::getInstance();
        // Create a new transaction
        $transaction = $catalog->createTransaction( $product );

        try
        {
            // Start transaction
            $transaction->begin();
            // Add new product to catalog
            $catalog->addProduct( $product );
            // Commit product transaction
            $transaction->commit();
            // Reset input
            $this->view->setText( "" );
        }
        catch ( mpProductInTransactionException $e )
        {
            // Show error message
            $this->showDialog( "Transaction Error", $e->getMessage() );
        }
        catch ( mpProductExistsException $e )
        {
            try
            {
                // Rollback product transaction
                $transaction->rollback();
                // Show error message
                $this->showDialog( "Name Error", $e->getMessage() );
            }
            catch ( mpProductTransactionNotOpenException $e )
            {
                // Show error message
                $this->showDialog( "Transaction Error", $e->getMessage() );
            }
        }
    }
?>

One weak point this example shows very well is that the controller has at least six dependencies to the business model. Since I assume that dependencies between a business model and the controller will occur more than one time in an application, which makes the maintenance of the business model source code very difficult. Another point that can happen is the need of another presentation layer for your complex business model. For web applications this requirement should be resolvable by the choice of a suitable frameworks, but in some situations it's conceivable that is not possible without larger expenditure. So I created a second GTK based presentation layer for the business model. The source code for this gtk frontend can be found here controller, view.

If we compare both doAddProduct() implementations we see that they are nearly identical except some minor differences due to the used technology. This produces further complexity for the application maintenance, which no one wants.

So! What can be done to solve this problem?

The simple answer to this question is, we have to decouple both layers. So we have to implement a simplified model controller(MC) that encapsulates the business model from the MVC. This technology is also well known under the terms Facade or Command. A very good description can be found in the Java J2EE Blueprints. The following listing shows the new domain/business facade.

<?php
class mpDomainFacade
{
    public function addProduct( $productName )
    {
        // Create a new product
        $product = new mpProduct( $productName );

        // Get the product catalog
        $catalog = mpProductCatalog::getInstance();
        // Create a new transaction
        $transaction = $catalog->createTransaction( $product );

        try
        {
            // Start transaction
            $transaction->begin();
            // Add new product to catalog
            $catalog->addProduct( $product );
            // Commit product transaction
            $transaction->commit();
        }
        catch ( mpProductInTransactionException $e )
        {
            throw new mpDomainException( "Transaction Error", $e->getMessage() );
        }
        catch ( mpProductExistsException $e )
        {
            try
            {
                // Rollback product transaction
                $transaction->rollback();
                // Show error message
                throw new mpDomainException( "Name Error", $e->getMessage() );
            }
            catch ( mpProductTransactionNotOpenException $e )
            {
                // Show error message
                throw new mpDomainException( "Transaction Error", $e->getMessage() );
            }
        }
    }
}

class mpDomainException extends RuntimeException
{
    private $title = "";

    public function __construct( $title, $message )
    {
        parent::__construct( $message );

        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }
}
?>

As you can see this new subsystem encapsulates the whole insert operation. Everything a client has to do is to pass the new product name into the component and the client must care about thrown mpDomainException objects. And here is the new doAddProduct() implementation from the web controller.

<?php
    public function doAddProduct()
    {
        $name = $this->view->getText();

        // Create a domain Facade
        $facade = new mpDomainFacade();

        try
        {
            // Try to add product
            $facade->addProduct( $name );
            // Reset input
            $this->view->setText( "" );
        }
        catch ( mpDomainException $e )
        {
            $this->showDialog( $e->getTitle(), $e->getMessage() );
        }
    }

The produced overhead is really limited, because the new facade uses same method calls as the original implementation. Even if the introduction of own Value-Objects for communication between Controller and Facade, which weren't used in the shown example, would result in an additional overhead, I have the opinion that the presented technology is important for all large and long running application.

The modified source code for the controllers and the facade can be found here: facade, web controller, gtk controller.

Since there are a many great applications that aren't working with the presented separation and that are very successful, I assume, that some of my readers will not agree with me. It is also possible that the shown technology is more java and not the php way of doing things. But when I was young, I smoked to much java

And now I invite you to discuss with me and I close this post with a citation from Arne Nordmann:

separate your concerns