PHP模式库需要的建议 - 调用方法和结构化组件

时间:2017-04-19 18:07:40

标签: php html css

您好我是OO PHP的新手,并试图制作我自己的小模式库。我需要一些关于如何构建组件的反馈。我目前正在使用echo()来生成HTML结构。这样做还有其他办法吗?此外,在模式库中创建依赖项是一种好的/可接受的做法,例如组件A调用组件B的方法。

例如我的Button组件:

<?php

class Button {

    public function __construct($type, $value, $location)
    {
        echo '<input type="button" class="'.$type.'" value="'.$value.'" onclick="location.href='. $location . '" />';
    }
    static function generate($type, $value, $location)
    {
        echo '<input type="button" class="'.$type.'" value="'.$value.'" onclick="location.href='. $location . '" />';
    }

}

在Jumbotron内召唤:

<?php
class Jumbotron {

    public function __construct($header, $paragraph) {
        echo '<div class="jumbotron" id="jumbo"><p>I am</p><h1>'.$header.'</h1><p>'.$paragraph.'</p>';
        Button::generate("primary","Latest Projects","'projects.php'");
        echo'</div>';
    }

}

最后一个问题:我无法在Jumbotron中调用__construct()方法,我不得不复制它并重命名它。这是一种正确的做法,还是我只是重新发明轮子?

1 个答案:

答案 0 :(得分:1)

这是没有静态调用

的简单方法
class Button {
    private $type;
    private $value;
    private $location;
    public function __construct($type, $value, $location)
    {
        $this->type = $type;
        $this->value = $type;
        $this->location = $type;

        //echo '<input type="button" class="'.$type.'" value="'.$value.'" onclick="location.href='. $location . '" />';
    }
    public function generate()
    {
        echo '<input type="button" class="'.$this->type.'" value="'.$this->value.'" onclick="location.href='. $this->location . '" />';
    }
}
$button1 = new Button("primary","Latest Projects","'projects.php'");
$button1->generate();

$button2 = new Button("primary2","Latest Projects2","'projects.php'");
$button2->generate();

静态方式

class Button {
    static function generate($type,$value,$location)
    {
        echo '<input type="button" class="'.$type.'" value="'.$value.'" onclick="location.href='. $location . '" />';
    }
}
Button::generate("button","aaaa","location");
Button::generate("button2","aaaa2","location2");

请查看工厂,外观,单件等不同设计模式。浏览设计模式教程 Link 1: Common Design patterns
PHP Design Patterns- Tutorials Point