Archive for Juli, 2009

Self-made MVC web application in PHP

Donnerstag, Juli 9th, 2009

While PHP makes it easy to build small and simple dynamic websites, a strict architecture is difficult to obtain. It simply is too easy to mix logic, presentation and data access. In this post I will describe how a strict MVC architecture can be implemented easily without a third party framework. I focus especially on separating business logic from presentation. Please note, that the code examples show simplified code and details, such as error handling need to be added for production.

The core concept is the Request class:

abstract class Request {
    function execute($template) {
        $params = $this->prepare();
        include $template;
        $this->cleanUp();
    }

    function prepare() {
    }

    function cleanUp() {
    }
}

By overriding the method prepare(), business logic will be implemented and passed as parameter array params to the template. Optionally the cleanUp() method can be implemented to clean up after displaying the template – for example closing database connections etc. An example would look like this:

class MyRequest extends Request {
    function prepare() {
        $params = array();
        // do something and fill the $params array
        return $params;
    }
}

Finally the MyRequest class will be instantiated and called with the template path:

$req = new MyRequest();
$req->execute('template.php');

With this simple approach, logic and presentation can be easily separated; the template code is very clean and uses only the $params array. The business logic is encapsulated and does not contain any presentation specific references.