php – Joomla! 如何在元件中快速取得 GET | POST 的方法
請先了解上一篇 如何設計共用的 Controller 做預處理,在 Component 中其實我們只要修改 Controller 繼承的 Library ,在裡面處理好 GET / POST 的處理,那麼之後就能更快速的使用例如
GET
1 2 3 4 |
$this->getString('task'); $this->getInt('id'); |
POST
1 2 3 4 |
$this->postString('title'); $this->postInt('category'); |
透過 Composer 安裝
我已經寫好套件 joomla_easy_request 了,請直接透過 Composer 下載使用吧。
1 2 3 |
composer require jsnlib/joomla_easy_request |
接著載入 composer autoload.php,如果要全域載入記得透過自訂 plugin 觸發 system 的 onAfterInitialise(),參考 如何自動載入類別庫或 composer 到全域 ,例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php defined('_JEXEC') or die; class plgSystemMylib extends JPlugin { public function __construct(&$subject, $config) { parent::__construct($subject, $config); } public function onAfterInitialise() { require_once JPATH_ROOT . '/vendor/autoload.php'; } } |
因為 Joomla! 目前 v3.8 有個詬病就是 vendor 無法自動載入 Trait 只能載入 Class,我沒有深入研究但猜想可能是使用了極為舊版的 Composer 所造成。所以我們要啟用 joomla_easy_request 必須這麼寫
1 2 3 4 5 6 7 8 |
new \Jsnlib\Joomla\EasyRequest; <-- 讓 Joomla! 自動載入對應的 class 文件 class TodoListControllerForm extends JControllerLegacy { use \Jsnlib\Joomla\EasyRequestTrait; <-- 使用特徵 Trait,也就是我們的程式碼主體 } |
範例是使用 controller,當然也可以在任何地方使用,例如 plugin
1 2 3 4 5 6 7 8 |
new \Jsnlib\Joomla\EasyRequest; class plgSystemHandicapfree extends JPlugin { use \Jsnlib\Joomla\EasyRequestTrait; } |
現在你可以輕鬆使用 post 或 get。
1 2 3 4 5 6 7 8 9 10 11 12 |
// 取得整個陣列 $this->post(); $this->postArray(); // 取得單一值,不轉換型態 $this->post('cid'); // 強制轉換型態 $this->postString('task'); $this->postInt('id'); |
也可以直接調用
1 2 3 4 5 6 |
$this->app; $this->input; $this->get; // 等同 $this->input->get; $this->post; // 等同 $this->input->post; |
像是上傳檔案需要用到 $_FILES 那麼則需要使用
1 2 3 4 5 6 7 |
$files = $this->input->files->get('jform', '', 'array'); foreach ($files['upl'] as $key => $file) { $filename = JFile::makeSafe($file['name']); } |
Nick
2018-05-20 - 15:59
想法不錯,但以Team work來看或許還有待討論。
換個角度想,如果其他人維護你的專案,是否真的有幫助到? 亦或者是要重新學一套新的寫法?
JSN
2018-05-21 - 10:31
如果維持舊專案的話就按照就專案的習慣就可以了,若是開發新專案的話可以考慮採用,或是個人接案、或是案子不大的小型專案或許也都會蠻適合的? 😀 當然可以提出一些思維,至於如何採用也就看大家選擇囉