美文网首页
swoole与laravel结合使用,不再裸奔

swoole与laravel结合使用,不再裸奔

作者: 空生Geek | 来源:发表于2017-02-13 10:14 被阅读0次

    我们在使用swoole搭建服务的时候,经常需要使用到一些常用的类库,而自己一个一个去找又太麻烦,如果还想用的优雅那可就要费上一番功夫了。
    如果大家跟我一样是个懒货,不烦将swoole跟某个框架结合起来使用,这样就可以尽情的享用框架为我们带来的便利了,下面介绍一下如何将swoole跟laravel结合使用。

    1.开启swoole命名空间

    使用命名空间类风格,需要修改php.ini,增加swoole.use_namespace=On开启。使用命名空间类名后,旧式的下划线风格类名将不可用。

    2.使用命令驱动

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use App\Repositories\PushRepository;
    
    class Push extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'push:start';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = '推送服务启动命令';
    
        /**
        * push处理推送任务的对象实例
        */
        protected $_repPush;
    
        /**
         * Create a new command instance.
         *
         * @param  DripEmailer  $drip
         * @return void
         */
        public function __construct(PushRepository $repPush)
        {
            parent::__construct();
            $this->_repPush = $repPush;
        }
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
          $this->_repPush->start();
        }
    
    
    }
    

    3.编写服务逻辑

    <?php
    /**
     * 消息推送服务
     * @author: KongSeng <643828892@qq.com>
     */
    namespace App\Repositories;
    use \Swoole\Server;
    use Config;
    
    class PushRepository extends BaseRepository
    {
    
      /**
      * Swoole Server 服务
      */
      private $__serv = null;
    
      /**
      * 构造函数
      */
      public function __construct(){
        $this->__initSwoole();
      }
    
      /**
      * 初始化swoole
      */
      private function __initSwoole(){
        $host = Config::get('swoole.host');
        $port = Config::get('swoole.port');
        $setConf = Config::get('swoole.set');
    
        $this->__serv = new Server($host,$port);
        $this->__serv->set($setConf);
    
        $this->__serv->on('receive', array($this,'onReceive'));
      }
    
      /**
      * 数据接收回调
      */
      public function onReceive($serv, $fd, $from_id, $data){
        $serv->send($fd,$data."\r\n");
      }
    
      /**
      * 开启服务
      */
      public function start(){
        $this->__serv->start();
      }
    
    
    }
    
    

    4.启动服务

    php artisan push:start

    相关文章

      网友评论

          本文标题:swoole与laravel结合使用,不再裸奔

          本文链接:https://www.haomeiwen.com/subject/rrpzittx.html