Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created August 14, 2018 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/695c3f8b688b5b8bc556f3bbac1ec122 to your computer and use it in GitHub Desktop.
Save yano3nora/695c3f8b688b5b8bc556f3bbac1ec122 to your computer and use it in GitHub Desktop.
[cakephp: Shell] Shell / Task class on CakePHP3. #php #cakephp

Shell / Task

Shell クラス
シェル用の共通クラスとして 「タスク」クラス を追加できます

<?php 
namespace App\Shell;

use Cake\Console\Shell;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Datasource\ConnectionManager;
use Cake\Filesystem\Folder;
use Cake\Filesystem\File;

/**
 * ExampleShell Class.
 *
 * @access public
 * @author hyano@ampware.jp
 * @package Shell
 * @link https://book.cakephp.org/3.0/ja/console-and-shells.html#namespace-Cake\Console
 */
class ExampleShell extends Shell
{


  /** 
   * Initialize instance for all methods.
   * @param  void
   * @return void
   */
  public function initialize() {
    parent::initialize();
    // Loading utilities.
    $this->Hasher     = new DefaultPasswordHasher();
    $this->Connection = ConnectionManager::get('default');
    $this->loadModel('Users');
  }

  
  /**
   * Printing welcome messages.
   * @param  void
   * @return void
   */
  public function startup() {
    // If you want to output welcome messages, override parent method like this.
    // parent::initialize();
  }
  
  
  /**
   * Option Parser.
   * @param  void
   * @return OptionParser
   */
  public function getOptionParser() {
    $parser = parent::getOptionParser();
    $parser->addOption('force', [
      'help'    => 'Skip interaction.',
      'short'   => 'f',
      'boolean' => true,
    ]);
    return $parser;
  }


  /** 
   * Main command for `$ bin/cake example`.
   * Method runs when executed without sub-command or args.
   * @param  void
   * @return void
   */
  public function main() {
    $this->out('Hello world.');   // Print stdout.
    $this->err('Error sample.');  // Print stderr.
    $this->out($this->nl(1));     // Print EOL.
    $this->hr();                  // Print horizon border like '----'.

    // To interact with user inputs.
    if (!$this->params['force']) {
      $isContinue = $this->in('Want to continue the process ?', ['y', 'N'], 'N');
      if ($isContinue !== 'y') {
        $this->abort('Process was canceled.');  // Print stderr with throw StopException.
      }
    }
    
    $users = $this->Users->find('all')
      ->where(['Users.email' => DEV_EMAIL]);
    if (empty($users)) $this->abort('Missing users.');
    $this->out($users->first());  // Can to pass object/array.
    
    // Create file.
    $json = json_encode($users->toArray());
    $this->createFile('user.json', $json);  // Refs: https://goo.gl/5JZ9AK
    
    // Execute another command.
    $this->dispatchShell([
      'command' => 'example hey_there john --verbose',
      'extra'   => ['foo' => 'bar'],  // Passing to Shell::param('foo')
    ]);
  }
  
  
  /**
   * Sub command for `$ bin/cake example hey_there {name}`.
   * @param  string $name
   * @return string $response
   */
  public function heyThere(string $name = 'Anonymous') {
    $this->out('Hey there, '.$name.' !');                     // Hey there, john !
    $this->out('Passed param is '.Shell::param('foo').' !');  // Passed param is bar !
    $this->verbose('This message is verbose output to print only using --verbose option.');  
    $this->quiet('This message is quiet output to print always.');  
  }


}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment