开发者

Trying to implement proper patterns in PHP, is this right?

The below code is something I just wrote up after reading a bit about design patterns and I want to know if I have the gist of it. This is supposed to implement a Mediator design pattern, as well as using interfaces over implementation and the Factory design pattern.

<?php
interface iNav_Walker
{
    public function walk();
}

class Nav_Walker
{
    public static function factory()
    {
        $class_name = 'Generic_Nav_Walker';
        $class_name = filter( 'nav_walker_class', $class_name ); 

        $object = new $class_name;

        return $object;
    }

    private function __construct()
    {
        return FALSE;       
    }
}

class Generic_Nav_Walker implements iNav_Walker
{
    public function walk() 
    {
        echo 'Generic Nav Walker';
    }
}

class Custom_Nav_Walker implements iNav_Walker
{
    public function walk() 
    {
        echo 'Custom Nav Walker';
    }
}

class MyPlugin 
{
    public static function use_custom_walker( $walker_class )
    {
        return 'Custom_Nav_Walke开发者_运维问答r';
    }
}

add_filter( 'nav_walker_class', array( 'MyPlugin', 'use_custom_walker_class' ) );

$nav_walker = Nav_Walker::factory();
$nav_walker->walk();

The obvious benefit of this approach is making it easy to replace an applications default class with a custom one. Your custom one could even extend the original class and just override a single method could it not? Like this:

<?php
class Generic_Nav_Walker implements iNav_Walker
{
    public function walk() 
    {
        echo 'Generic Nav Walker';
    }

    public function other_func()
    {
        // Do something
    }

    public function other_func2()
    {
        // Do something
    }
}

class Custom_Nav_Walker extends Generic_Nav_Walker implements iNav_Walker
{
    public function walk() 
    {
        echo 'Custom Nav Walker';
    }
}

Because you may only wish to change some small part of the class, or is this bad practice?


Trying to implement proper patterns in PHP, is this right?

No, no need to look at your code to realise you don't understand what patterns are.

A pattern is what your code is - not what it should be or any sort of template. It is a quick way of describing the abstract functionality of module. And therefore a useful tool for describing code and for planning a curriculum around.

Planning and implementing your project as a set of patterns is a very misguided approach to software engineering / deveopment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜