LoginSignup
0
1

More than 3 years have passed since last update.

codeigniterでthird_party内のcontrollerを使う

Posted at

codeigniterのthird partyは便利です。色々なものをモジュール化して分けておける。configとかも、ある程度だいたいできちゃう。

けれどもコントローラーだけはだめ。なぜならコントローラーからthird partyを始めとした大体のクラスを読んじゃっているから。

けれどもthird partyにコントローラーとかを含めちゃって使い回せるようにしたい!!

というわけでやりましょう。

事前にファイルをrequireする

まあ、単純です。controllerファイルの先頭でthird party内のコントローラーを読み込んで、それをextendsするだけ。

まず、third party内に読み込むためのコントローラーを作ります。

application/third_party/test/controllers/Welcome_preset.php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome_preset extends CI_Controller{
    public function index(){
           $this->load->view('welcome_message');
    }
}

次に、実際に参照されるコントローラー。

application/controllers/Welcome.php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . "third_party/test/controllers/Welcome_preset.php";

class Welcome extends Welcome_preset{
    public function __construct(){
        parent::__construct();
    }
}

これで、Welcomeコントローラーに接続される時に実行されるのは継承元のWelcome_presetクラスのものとなります。

そのプロジェクトだけで利用したい関数とかを作りたかったら、参照先のWelcomeに書けばいいし、汎用的なのはpresetに、と取り回ししやすい形で運用できます。いえいいえい。

考え方はシンプルで、

接続

Welcome.php

Welcome_preset.php呼び出し

Welcome_presetを継承したWelcomeクラス実行

という感じ。

ソーシャルログイン系とか、自分の中で作り方が決まっててもうコントローラーまるまるコピペっとしてるやつとか、ちょっとした改変でOKとかってなってるものをこれで一括管理できます。楽ちんまるです。

さらに、Welcome_presetでMY_Contollerを継承するようにしておけば、

MY_Controller → Welcome_preset → Welcomeと、呼び出せるのでこれまた便利です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1