Swoole 与 Laravel 结合使用,更加优雅


我们在使用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


点赞 取消点赞 收藏 取消收藏

<< 上一篇: 以太坊PHP离线交易开发包

>> 下一篇: Redis 在 Laravel 项目中的应用实例详解,可参考学习下