LoginSignup
3
4

More than 5 years have passed since last update.

[CakePHP 2.x] ComponentでConstructorを使う、ついでにShellからComponentを使うまとめ

Posted at

cakephp?でのコンストラクタの使い方をメモ。

まずComponentの方。

AsagohanComponent.php
<?php
App::uses('Component', 'Controller');

class AsagohanComponent extends Component {

    const BURNER_ACCESSKEY = "hidarihajinaraok";
    const BURNER_SECRETKEY = "jikkurimawasu";
    const BURNER_REGION = "hidarihaji";

    private $_ochawan;
    private $_owan;
    private $_burner;

    public function __construct(ComponentCollection $collection, $settings = array()) {
        // Burnerオブジェクト作成
        try {
            $this->_burner = Burner::factory(array(
                'key' => self::ACCESS_KEY,
                'secret' => self::SECRET_KEY,
                'region' => self::REGION
            ))->get('burner');
        } catch (S3Exception $e) {
            throw new CakeException($e, Configure::read('AsagohanErrorCode.cannot_use_burner'));
        }

        $this->_ochawan = "zakkokumai"
        $this->_owan = 'omisoshiru' . $this->_ochawan;

        parent::__construct($collection, $settings);
    }

    // Getter
    public function getOchawan() {
        return $this->_ochawan;
    }

    // Getter
    public function getOwan() {
        return $this->_owan;
    }

これを Console/NeokiShell.php から呼び出します。

Console/NeokiSHell.php
<?php
App::uses("ComponentCollection", "Controller");
App::uses("AsagohanComponent", "Controller/Component");

class NeokiShell extends AppShell {
    public function startup() {
        $collection = new ComponentCollection();
        $this->Asagohan = new AsagohanComponent($collection);
        parent::startup();
    }

    public function main() {
        $gohannisuru = $this->Asagohan->getOchawan();
        $shirumono = $this->Asagohan->getOwan();
    }

}

こんな感じ。
少しコードがスッキリするかな。

3
4
1

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
3
4