Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

[CakePHP 2.x] shell(シェル)からComponent(コンポーネント)を呼び出す

More than 5 years have passed since last update.

cake初めて一週間。shellからComponentを呼び出したいところで、コツがあったのでメモ。
OnakahettaShell.php から TamagoyakiComponent.php を呼び出します。

<?php
App::uses('ComponentCollection', 'Controller'); //これが大事
App::uses('TamagoyakiComponent', 'Controller/Component'); 
// ↑このHogeComponentとapp/Controller/Component以下の呼び出したいファイルの『クラスの名前』が一致しているか確認。(まあ基本はクラスとファイル名は一致させる)

/**
* こういうクラス ちなみにAppShellがShellを継承している
*/
class OnakahettaShell extends AppShell {

    /**
    * TamagoyakiComponent.phpの呼び出し
    */
    public function startup() {
        $collection = new ComponentCollection(); //これが大事です。
        $this->Hoge = new TamagoyakiComponent($collection); //コンポーネントをインスタンス化
        parent::startup();
    }

    /**
     * メイン処理
     */
    public function main() {
        $monya = $this->Tamagoyaki->__fuga(); 
        //↑こんな感じで使えます◎

        Debugger::log($this); // 出力内容は下に記載
        Debugger::log($this->Tamagoyaki); //出力内容は下に

ちなみにAppShellはShellを継承しています。

app/console/Command/AppShell.php
<?php
App::uses('Shell', 'Console');
class AppShell extends Shell {
}
Debugger
object(OnakahettaShell) {
        uses => array()
         .
         .
        Tamagoyaki => object(TamagoyakiComponent) {} <-いた!!
         .
         .
}
Debugger
object(TamagoyakiComponent) {
        components => array()
        settings => array()
        [protected] _Collection => object(ComponentCollection) {}
        [protected] _componentMap => array()
}
colorrabbit
creator.
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away