php – Joomla! – 如何設計共用的 Controller 做預處理

不管是不同 Component 下的 Controller,或是同個 Component 底下的 Controller,很多時候我們需要每個 Controller 都得處理共用程序,而不打算每次開新的 Controller 就要從寫一次

例如這個 $input,我可不想每次寫 Controller 都還要寫一次

$input = \JFactory::getApplication()->input;
echo $input->post->getString('task');

我希望每次寫 Controller 只需要

$this->post->getString('task');

或是有個 Model 因為太常使用,我們卻每個 Controller 都要載入

$this->something_model = $this->getModel('something') or die("Invalid Load Model");

我們可能會很希望直接在 controller::method() 中直接使用

$somethings = $this->somethings_model->getAll();

這樣該如何製作?

其實只要透過 plugins 的方式就可以達到,可以先參考這篇 如何自動載入類別庫或 composer 到全域 。我們依照這篇文章的 plugin 設計實做。

建立一個 Library

libraries/src/Jsnlib/Joomla/ControllerLegacy/Form.php

<?php 
namespace Jsnlib\Joomla\ControllerLegacy;

class Form extends \JControllerLegacy
{
    protected $app;
    protected $input;
    protected $get;
    protected $post;

    function __construct($config = array())
    {
        parent::__construct($config);

        $this->app = \JFactory::getApplication();
        $this->input = $this->app->input;
        $this->get  = $this->input->get;
        $this->post = $this->input->post;
    }
}

 

注意自動讀取的類別

這個類別如同這篇 如何自動載入類別庫或 composer 到全域 ,我們不需要修改

plugins/system/mylib/mylib.php

<?php
defined('_JEXEC') or die;

class plgSystemMylib extends JPlugin
{
    public function __construct(&$subject, $config)
    {
        parent::__construct($subject, $config);
    }

    public function onAfterInitialise()
    {
        // ...... 
        
        // 這行注意要存在
        JLoader::registerNamespace('Jsnlib', JPATH_LIBRARIES . '/src');
        
        // ...... 
    }
}

 

實際測試

元件 Component 注意繼承改為 extends \Jsnlib\Joomla\ControllerLegacy\Form。

components/com_todolist/controllers/form.php

<?php
defined('_JEXEC') or die;

class TodoListControllerForm extends \Jsnlib\Joomla\ControllerLegacy\Form
{
    function __construct($config = array())
    {
        parent::__construct($config);
    }

    public function query_insert()
    {
        // 如預期顯示
        echo $this->get->getString('task');
        echo $this->post->getString('title');
        die;
    }
}

 

接著我們如果覺得這樣取出 GET/POST 太囉嗦

$this->get->getString('task');
$this->post->getString('title');

我想更精簡這樣

$this->getString('task');
$this->getInt('id');

$this->postString('title');
$this->postString('description');

那就參考下一篇文章 如何在元件中快速取得 GET | POST 的方法

Comments

發表迴響