如何在CodeIgniter中实现观察者模式以用于通用任务

5
我正在使用经典的CI MVC架构构建一个应用程序,用户有一个通用任务列表。任务的主要目的是指示用户完成特定操作,并将其重定向到需要完成此操作的页面。
在非常简单的情况下,任务的数据库模式如下所示: enter image description here 任务列表本身将是一个重定向用户的列表: enter image description here 我的问题是当用户被重定向到需要发生操作的特定页面时,我们失去了特定任务的上下文。因此,即使任务已完成(在此示例中,例如上传文档),该任务本身也不知道这一点,我们没有连接来更新任务。
经过一番研究,观察者设计模式似乎是可以满足这个需求的。但是在所有例子中,我都没有理解如何将其实际应用到我们当前的系统中。
在控制器中处理文档上传的函数upload_doc(){},当成功执行时,还应该更新与该文档上传相关或订阅的任务。
class Dashboard extends MY_Controller{

public function __construct()
{
    parent::__construct();

    // Force SSL
    $this->force_ssl();
}

public function upload_doc(){
   //Handle doc upload and update task
}
}

有人能以适合新手的方式帮助我在CI框架中实现这个设置吗?

提前感谢!


有一些教程可以让你了解如何在PHP中实现观察者模式。你可以在这里阅读:https://www.php.net/manual/en/class.splobserver.php - Felippe Duarte
2个回答

0

如果涉及到设计模式,我总是尝试寻找一个参考文档或者GitHub仓库,其中包含所需语言的设计模式示例。对于PHP,我可以热情地推荐这个:

https://designpatternsphp.readthedocs.io/en/latest/Behavioral/Observer/README.html

一个示例实现可能看起来像这样。注意:我没有使用CodeIgniter的经验。这只是一种说明如何使用给定的代码示例实现它的方式。
class Dashboard extends MY_Controller 
{
    private function makeFile()
    {
        // I would put this method into a file factory within your container.
        // This allows you to extend on a per module-basis.

        $file = new File();        
        $file->attach(new UpdateTask);
        $file->attach(new DeleteFileFromTempStorage);
        $file->attach(new IncrementStorageSize);
        $file->attach(new AddCustomerNotification);
        return $file;
    }

    public function upload_doc() 
    {
        // My expectation is that you have some task-id reference 
        // when uploading a file. This would allow all observers 
        // to "find" the right task to update.
        $file = $this->newFile();

        // enhance your file model with your request parameters
        $file->fill($params);

        // save your file. Either your model has this functionality already
        // or you have a separated repository which handles this for you.
        $fileRepo->persist($file);

        // Finally notify your observers
        $file->notify();  
    }
}

希望这能有所帮助。

0
如果我正确理解了您的问题和意图(在一个地方创建记录并在其他地方发生某些操作之间建立关系),那么观察者模式(如果我们指的是同一本书中的同一种想法)无法解决它,因为PHP和Web的通用无状态性质,即执行跨越多个程序调用。GoF书中的经典模式是为单个程序内的单个执行而设计和预期的。
您需要编写自定义逻辑,将任务记录和用户后续操作绑定在一起。最简单的方法是向用户浏览器添加一个cookie,其中包含任务ID,以便该ID可被文档上传控制器访问,并更新系统的其余部分。在那里,您可以像Christoph的答案或互联网上的任何其他示例一样使用经典的观察者模式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接