【问题标题】:PHP Call method at end of chain链末尾的PHP调用方法
【发布时间】:2014-09-02 17:36:39
【问题描述】:

我有一个利用单例原理的类,并且我有允许链接的方法。最后,您必须调用 output() 方法来呈现该类,但我想知道是否有任何方法可以自动执行此操作。我试过使用 __destruct,但它处理得很晚。我需要在脚本退出之前完成它。

class View {

private static $_instance = null,
               $_view;

public static $data;

private static function getInstance()
{
    // Instantiate the class
    if( self::$_instance === null ){
        self::$_instance = new self;
    }
    return self::$_instance;
}
public static function make( $view )
{
    $instance = self::getInstance();
    $file = explode( '.', $view );
    $file = DIR . 'core/views/' . $file[0] . '/' . $file[1] . '.php';
    self::$_view = $file;
    return $instance;
}
public function with($data)
{
    self::$data = $data;
    return $this;
}

}

它会像这样使用:

return View::make($view)->with($data);

【问题讨论】:

  • PHP 中的单例与暑假穿雪鞋一样有意义:PHP 是无状态的,单例只是伪装的全局变量。为什么不创建三个全局函数,然后将您需要的内容传递给它们?
  • 你应该看看 Laravel 源代码,因为它看起来像是你在尝试模仿它。
  • @true 哈哈,好猜!我正在尝试在 WP 插件中利用它的结构。

标签: php chaining


【解决方案1】:

我假设有一些东西在期待返回值,并将其回显(例如控制器)?如果是这样,您可以为您的 View 类使用 __toString() 魔术方法:

public function __toString()
{
    return $this->output();
}

理论逻辑:

$view = $controller->getIndex() // Returns your View instance
echo $view; // Magically converted to a string

旁注,您也可以将其与投射一起使用:

$view = (string) View::make($view)->with($data); // will be the rendered view

关于__toString() 需要注意的重要一点是不能在函数内抛出异常(即您的视图不能抛出异常)。如果抛出一个,PHP 实际上会抛出一个不太有用的“__toString() 不能抛出异常”异常。

【讨论】:

  • +1 我本来打算这么建议的,但为什么不直接echo View::make($view)->with($data);
【解决方案2】:

您可以使用__call(),但这需要$this 上下文。

public function __call($method, $args)
{
    // ...
    // check if the current method being called is the last one needed, then
    // render the view output
    if ('lastMethod' == $method) {
        $this->render();
    }
}

在此示例中,如果您知道在视图渲染发生之前需要调用的最后一个方法的名称​​,那么您可以自动调用它。尽管如此,我还是建议您重写大部分 View 类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多