標籤:class root word php use 相同 text str control
第一步:將Workerman複製到ThinkPHP項目中的適當位置(我是放到根目錄,與ThinkPHP平級)
第二步:將Workerman中的所有檔案(除/Workerman/Lib/Constants.php外)尾碼改為.class.php,如:Worker.php改為Worker.class.php
第三步:配置ThinkPHP的命名空間自動載入。在ThinkPHP的設定檔中加入
‘AUTOLOAD_NAMESPACE‘ => array( ‘Workerman‘ => ROOT_PATH . ‘Workerman‘,//根據自己的存放位置修改)
第四步:在ThinkPHP項目中新增Worker模組和Worker控制器,也可以根據自己的喜好來命名
namespace Worker\Controller;use Workerman\Worker;class Worker { public function Start() { $worker = new Worker(‘text://0.0.0.0:1234‘); //執行個體化Worker,並設定協議、IP和連接埠 $worker->count = 4; $worker->onMessage = array($this, ‘onMessage‘); //worker的其它回調方法可以參考onMessage Worker::runAll(); } public function onMessage($connection, $data) { $connection->send(‘something...‘); }}
在onMessage方法中,還可以根據自訂的協議和內容格式,通過ThinkPHP的A()方法來調用相關的模組、控制器,就可以做到跟普通的ThinkPHP項目相同的開發模式了,如:
$class = A($data[‘m‘] . ‘/‘ . $data[‘c‘]);if (!$class) { $connection->send(‘Module or Controller not found.‘);} else { $action = $data[‘a‘]; unset($data[‘m‘], $data[‘c‘], $data[‘a‘]); try { call_user_func_array(array($class, $action), $data); } catch (Exception $ex) { throw $ex; }}
第五步:ThinkPHP入口綁定。入口綁定是ThinkPHP3.2.1+給出的方法,之前的版本也有相應的方法,網上是可以查得到的。
建立入口檔案worker.php
define(‘APP_PATH‘,‘./Application/‘);
define(‘BIND_MODULE‘, ‘Worker‘);define(‘BIND_CONTROLLER‘, ‘Worker‘);define(‘BIND_ACTION‘, ‘Start‘)//ThinkPHP的其他設定require ‘./ThinkPHP/ThinkPHP.php‘;
最後:通過bat檔案運行worker.php檔案(Windows環境直接運行會報錯)
thinkphp3.2整合workerman 多入口模式(windows)