在PHP控制器中调用模型功能的最佳选择 [英] The best option for calling model functionality in a PHP controller

查看:96
本文介绍了在PHP控制器中调用模型功能的最佳选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP构建自定义MVC框架.我的问题是当我想通过控制器类访问任何模型类时.我看到这样做的一种方式是通过使用诸如get和set之类的魔术方法的注册表设计模式,尽管有些人认为PHP get和set是不好的做法.我已经阅读了有关通过容器进行依赖项注入的信息,但是由于容器将不得不调用模型或者它必须包含将破坏MVC的目的并创建庞大的超类的模型,因此我无法有效地看到此工作.辛格尔顿被认为是不好的作法.我提到的方法是否有解决方案或改进的方法.这可能只是我对PHP的了解和需要改进的知识.

I am building a custom MVC framework using PHP. My problem is when I want to access any model class through the controller class. One way I have seen this done is through a registry design pattern using magic methods such as get and set, though PHP get and set are considered bad practise by some. I have read about dependency injection done through a container, but I can not see this working effectily as the container would have to call the models or it would have to contain the models which would defeat the purpose of MVC and create a massive super class. Singleton is seen as bad practise. Is there any solutions or improvements of the methods I have mentioned. It may just be my understand and knowledge of PHP needs improving.

当前我有这个:router.php(通过GET变量加载controllor

Currently I have this: router.php (loads up controllor through a GET varible

 <?php

class router {



function __construct() {

    if (file_exists("controller/".$_GET['url']."Controller.php"))  {


       function __autoload($controller) {

           $controlinclude = "controller/".$controller.".php";
            include $controlinclude;

      }
       $control = $_GET['url']."Controller";
        new $control();


    }
    else    {

        // throw exception
    }

}

}
?>

有希望的希望

推荐答案

首先...不要在路由机制中放置自动加载脚本.您正在混合责任.您最好基于 spl_autoload_register .

First of all ... Do no put autoloading script in routing mechanism. You are mixing the responsibilities. You will be better off creating a separate class for this based on spl_autoload_register.

Neeext ..不要对构造函数进行复杂的操作.这使您的代码有些不可测.也许您应该像这样:

Neeext .. do no put complicated operations on constructor. It is makes you code somewhat untestable. Maybe you should be something like:

// you might want to replace $_GET with $_SERVER['QUERY_STRING'] later
$router = new Router( $_GET['url'] );

// where 'default' is the name of fallback controller
$controller_class = $router->get_controller( 'default' );
$method_name = $router->get_action( 'index' );

$model_factory = new ModelFactory( new PDO( ... ) );
$controller = new {$controller_class}( $model_factory );
$controller->{$method_name}();

此外,您应该查看php 命名空间.用...Controller结尾的类毫无意义,只是想知道该类将位于何处.

Additionally, you should look into php namespaces. There is no point in ending class with ...Controller just to know where the class will be located.

好吧……回到模型.

在Web开发社区中,人们对模型存在一种非常普遍的误解(我将此归咎于RoR). MVC中的模型不是类,而是包含大量实例的应用程序层.大多数实例属于两种类型的类之一.承担以下职责:

There is quite common misconception about models in web development community ( i blame RoR for this mess ). Model in MVC is not a class, but an application layer which contains multitude of instances. Most of the instances belong to one of two types of classes. With following responsibilities:

  • 域逻辑:

处理所有计算,计算和所有特定于域的详细信息.该组中的对象不知道数据的实际存储位置和存储方式.他们只操纵信息.

Deals with all the computation, calculation and all the domain specific details. Objects in this group have no knowledge of where and how data is actually stored. They only manipulate the information.

数据访问

通常由适合 DataMapper 模式的对象组成(请勿与同名的ORM混淆. . 没有任何共同之处).负责存储和检索域对象中的数据.可能在数据库中.这就是您的SQL查询所在的位置.

Usually made of objects that fit DataMapper pattern (do not confuse with ORM of same name .. nothing in common). Responsible for storing data from Domain Objects and retrieving them. Might be in database.. might not. This is where your SQL queries would be.

在半现实世界中()可能看起来像这样(与代码重复相关):

In semi-real world situation () it might looks something like this (related to code abowe):

class SomeController
{
   // ... snip ...
   protected $model_factory = null;
   // ... snip ...

   public function __construct( ModelFactory $factory )
   {
       $this->model_factory = $factory;
   }
   // ... snip ...

   public function action_foobar()
   {
      $user = $this->model_factory->build_object( 'User' );
      $mapper = $this->model_factory->build_mapper( 'User' );

      $user->set_id(42);
      $mapper->fetch($user);

      if ( $user->hasWarning()  )
      {
          $user->set_status( 'locked' );
      }

      $mapper->store( $user );
   }

   // ... snip ...
}

如您所见,没有迹象表明数据是如何存储的.用户帐户是新帐户还是已经存在的帐户都没有关系.

As you see, there is no indication how the data was stored. It does not even matter if user account was new, or already existing.

一些您可能会觉得有用的材料

Some materials you might find useful

视频

  • Advanced OO Patterns (slides)
  • Clean Code Talks: Don't Look For Things!
  • Clean Code Talks: Unit Testing
  • Clean Code Talks: Global State and Singletons

书籍:

  • Real-World Solutions for Developing High-Quality PHP Frameworks and Applications
  • Patterns of enterprise application architecture
  • Clean Code: A Handbook of Agile Software Craftsmanship
  • SQL Antipatterns: Avoiding the Pitfalls of Database Programming

这篇关于在PHP控制器中调用模型功能的最佳选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆