案件の事情により、CodeIgniterをCLIからもWEBからも利用しなければならないという問題にぶち当たる。
CodeIgniterでは、
system/libraries/Router.php
で実行するコントローラとメソッドを指定しているので、これを拡張してやれば、行ける気がする。
今回のコマンドは、
index.php "ディレクトリ" "クラス" "実行するメソッド"
と指定することにした。
まず、Router.phpの拡張を作る。
system/application/libraries/MY_Router.php
を作成し、そのなかに以下のようなクラスを作成する。
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class EB_Router extends CI_Router{
//ここに後述のメソッドを書く。
}
?>
「//ここに後述のメソッドを書く。」の部分に後述のメソッドを書きます。
続いて、コマンドライン引数からコントローラーなどを指定するメソッドを拡張します。
system/libraries/Router.php
の「_validate_request」メソッドを、
system/application/libraries/MY_Router.php
へコピーします。
そして、このメソッドの冒頭へ、
CLIでの起動だった場合に、コマンドラインからコントローラーを指定するコードを書きます。
function _validate_request($segments){
/**********************************************************/
if( PHP_SAPI == 'cli' )
{
//ここでコントローラーなどを指定。
$this->set_directory($_SERVER['argv'][1]);
$this->set_class($_SERVER['argv'][2]);
$this->set_method($_SERVER['argv'][3]);
//カレントディレクトリを変更しておく
chdir( FCPATH );
return array();
}
/**********************************************************/
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if(is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Can't find the requested controller...
show_404($segments[0]);
}
/**********************************************************/
で囲まれた部分が追加した部分です。
これで、コマンドからコントローラーやメソッドを指定できます。
定義済み定数の「PHP_SAPI」に「cli」が指定されたとき以外は、
通常のルーティングが行われるので、
CLIとWEBでハイブリッドな使い方ができそうです。
注意点としては、
上記のコードは、コマンドから渡された、
ディレクトリやらコントローラーやらメソッドが、
確実に存在するという前提で書いています。
実際に使う場合は、このへんのエラートラップもしておいたほうがいいでしょう。
拡張のヒントとしては、上記のコードでは、第4引数以降はと特になにもしていないですが、
ここも拾って、実行メソッドの引数として渡せると楽しいかもです。
何かの参考になればー。
Comment feed