27
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-04-11

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::log($this)
object(OnakahettaShell) {
        uses => array()
         .
         .
        Tamagoyaki => object(TamagoyakiComponent) {} <-いた!!
         .
         .
}
Debugger::log($this->Tamagoyaki)
object(TamagoyakiComponent) {
        components => array()
        settings => array()
        [protected] _Collection => object(ComponentCollection) {}
        [protected] _componentMap => array()
}
27
22
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
27
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?