在PHP MVC中实现控制器的简洁方法

时间:2016-12-25 22:38:21

标签: php oop model-view-controller controller

我是PHP初学者(但我有一些Java EE背景)我想创建一个简单的博客,但我想通过使用PHP OOP MVC和优秀/最佳实践来实现,我是还在考虑如何做事,但我真的坚持如何实现Controller的想法,以及它如何与视图进行通信,我发现它与Java EE非常不同,我不知道知道在哪里或如何开始。

让我告诉你我是如何计划让它发挥作用的,至少直到控制器"部分:

  • 最终设计将是:

DB <-> DAO <-> Service <-> Controller <-> View. 但我会让这个例子变得简单。

这里我们有一个与DB通信的DAO类。

class UserDAO {

    private $db;

    // something like this by injecting the database object
    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function findUserById($id) {
        $req = $db->query("SELECT * FROM user WHERE id = $id");
        //.. etc
        //.. don't worry about the syntax, what matters is that we're returning the user Object that we found.
        return $user;

    }
}

控制器将是这样的:

class Controller {

    private $dao;

    public function __construct(UserDAO $dao) {
        $this->dao = $dao;
    }

    public function loadUser($id) {
        return $this->dao->findUserById($id);
    }
}

现在,让我们说我有一个index.php视图文件,如何在页面上显示$user个信息,或者如果我想要在视图中将数据从视图发送到控制器使用最佳实践保存$user,而不仅仅是require控制器功能中的视图等。

非常感谢你!

1 个答案:

答案 0 :(得分:1)

您可以使用控制器功能来要求使用输出缓冲区。

/**
 * Renders a view file as a PHP script.
 *
 * This method treats the view file as a PHP script and includes the file.
 * It extracts the given parameters and makes them available in the view file.
 * The method captures the output of the included view file and returns it as a string.
 *
 * This method should mainly be called by view renderer or [[renderFile()]].
 *
 * @param string $_file_ the view file.
 * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
 * @return string the rendering result
 */
public function renderPhpFile($_file_, $_params_ = [])
{
    ob_start();
    ob_implicit_flush(false);
    extract($_params_, EXTR_OVERWRITE);
    require($_file_);
    return ob_get_clean();
}

取自https://github.com/yiisoft/yii2/blob/master/framework/base/View.php#L149