前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用easyswoole进行开发web网站

使用easyswoole进行开发web网站

作者头像
仙士可
发布2019-12-19 14:13:49
1.5K0
发布2019-12-19 14:13:49
举报
文章被收录于专栏:仙士可博客仙士可博客

easyswoole作为swoole入门最简单的框架,其框架的定义就是适合大众php,更好的利用swoole扩展进行开发,

以下是本人使用easyswoole,看easyswoole文档总结出来的,关于easyswoole开发普通web网站的一些步骤

看下文之前,请先安装easyswoole框架

本文适用于es2.x版本,现在es3.x版本已经完全稳定,文档,demo完善,可移步www.easyswoole.com

查看文档以及demo

也可查看最新文章:easyswoole快速实现一个网站的api接口程序

一:使用nginx代理easyswoole  http

nginx增加配置:

代码语言:javascript
复制
server {
    root /data/wwwroot/;
    server_name local.easyswoole.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "keep-alive";
        proxy_set_header X-Real-IP $remote_addr;
        if (!-e $request_filename) {
             proxy_pass http://127.0.0.1:9501;
        }
        if (!-f $request_filename) {
             proxy_pass http://127.0.0.1:9501;
        }
    }
}

二:使用nginx访问静态文件

只需要在easyswoole根目录下增加一个Public文件夹,访问时,只需要访问域名/Public/xx.css

如图:

三:引入自定义配置

1: 在App/Config/下增加database.php,web.php,config.php

2:在全局配置文件EasySwooleEvent.php中参照以下代码:

代码语言:javascript
复制
<?php

namespace EasySwoole;

use \EasySwoole\Core\AbstractInterface\EventInterface;
use EasySwoole\Core\Utility\File;

Class EasySwooleEvent implements EventInterface
{

    public static function frameInitialize(): void
    {
        date_default_timezone_set('Asia/Shanghai');
        // 载入项目 Conf 文件夹中所有的配置文件
        self::loadConf(EASYSWOOLE_ROOT . '/Conf');
    }

    public static function loadConf($ConfPath)
    {
        $Conf  = Config::getInstance();
        $files = File::scanDir($ConfPath);
        if (!is_array($files)) {
            return;
        }
        foreach ($files as $file) {
            $data = require_once $file;
            $Conf->setConf(strtolower(basename($file, '.php')), (array)$data);
        }
    }
}

3:调用方法:

代码语言:javascript
复制
    // 获得配置
    $Conf = Config::getInstance()->getConf(文件名);

四:使用ThinkORM

1:安装

代码语言:javascript
复制
composer require topthink/think-orm

2:创建配置文件

在App/Config/database.php增加以下配置:

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2018/7/19
 * Time: 17:53
 */
return [
    'resultset_type' => '\think\Collection',
    // 数据库类型
    'type' => 'mysql',
    // 服务器地址
    'hostname' => '127.0.0.1',
    // 数据库名
    'database' => 'test',
    // 用户名
    'username' => 'root',
    // 密码
    'password' => 'root',
    // 端口
    'hostport' => '3306',
    // 数据库表前缀
    'prefix' => 'xsk_',
    // 是否需要断线重连
    'break_reconnect' => true,
];

3:在EasySwooleEvent.php参照以下代码

代码语言:javascript
复制
<?php

namespace EasySwoole;

use \EasySwoole\Core\AbstractInterface\EventInterface;
use EasySwoole\Core\Utility\File;

Class EasySwooleEvent implements EventInterface
{

    public static function frameInitialize(): void
    {
        date_default_timezone_set('Asia/Shanghai');
        // 载入项目 Conf 文件夹中所有的配置文件
        self::loadConf(EASYSWOOLE_ROOT . '/Conf');
        self::loadDB();
    }

    public static function loadDB()
    {
        // 获得数据库配置
        $dbConf = Config::getInstance()->getConf('database');
        // 全局初始化
        Db::setConfig($dbConf);
    }
}

4:查询实例

和thinkphp5查询一样

代码语言:javascript
复制
Db::table('user')
    ->data(['name'=>'thinkphp','email'=>'thinkphp@qq.com'])
    ->insert();    Db::table('user')->find();Db::table('user')
    ->where('id','>',10)
    ->order('id','desc')
    ->limit(10)
    ->select();Db::table('user')
    ->where('id',10)
    ->update(['name'=>'test']);    Db::table('user')
    ->where('id',10)
    ->delete();

5:Model

只需要继承think\Model类,在App/Model/下新增User.php

代码语言:javascript
复制
namespace App\Model;

use App\Base\Tool;
use EasySwoole\Core\AbstractInterface\Singleton;
use think\Db;
use think\Model;

Class user extends Model
{
  
}

即可使用model

代码语言:javascript
复制
 use App\Model\User;
 function index(){
    $member = User::get(1);
    $member->username = 'test';
    $member->save();
    $this->response()->write('Ok');}

五:使用tp模板引擎

1:安装

代码语言:javascript
复制
composer require topthink/think-template

2:建立view基类

代码语言:javascript
复制
<?php

namespace App\Base;

use EasySwoole\Config;
use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Request;
use EasySwoole\Core\Http\Response;
use EasySwoole\Core\Http\Session\Session;
use think\Template;

/**
 * 视图控制器
 * Class ViewController
 * @author  : evalor <master@evalor.cn>
 * @package App
 */
abstract class ViewController extends Controller
{
    private $view;
    
    /**
     * 初始化模板引擎
     * ViewController constructor.
     * @param string   $actionName
     * @param Request  $request
     * @param Response $response
     */
    public function __construct(string $actionName, Request $request, Response $response)
    {
        $this->init($actionName, $request, $response);
//        var_dump($this->view);
        parent::__construct($actionName, $request, $response);
    }
    
    /**
     * 输出模板到页面
     * @param  string|null $template 模板文件
     * @param array        $vars 模板变量值
     * @param array        $config 额外的渲染配置
     * @author : evalor <master@evalor.cn>
     */
    public function fetch($template=null, $vars = [], $config = [])
    {
        ob_start();
        $template==null&&$template=$GLOBALS['base']['ACTION_NAME'];
        $this->view->fetch($template, $vars, $config);
        $content = ob_get_clean();
        $this->response()->write($content);
    }
    
    /**
     * @return Template
     */
    public function getView(): Template
    {
        return $this->view;
    }
    
    public function init(string $actionName, Request $request, Response $response)
    {
        $this->view             = new Template();
        $tempPath               = Config::getInstance()->getConf('TEMP_DIR');     # 临时文件目录
        $class_name_array       = explode('\\', static::class);
        $class_name_array_count = count($class_name_array);
        $controller_path
                                = $class_name_array[$class_name_array_count - 2] . DIRECTORY_SEPARATOR . $class_name_array[$class_name_array_count - 1] . DIRECTORY_SEPARATOR;
//        var_dump(static::class);
        $this->view->config([
                                'view_path' => EASYSWOOLE_ROOT . DIRECTORY_SEPARATOR . 'App' . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . $controller_path,
                                # 模板文件目录
                                'cache_path' => "{$tempPath}/templates_c/",               # 模板编译目录
                            ]);
        
//        var_dump(EASYSWOOLE_ROOT . DIRECTORY_SEPARATOR . 'App' . DIRECTORY_SEPARATOR . 'Views' . DIRECTORY_SEPARATOR . $controller_path);
    }
    
}

控制器继承ViewController类

代码语言:javascript
复制
<?php

namespace App\HttpController\Index;

use App\Base\HomeBaseController;
use App\Base\ViewController;
use EasySwoole\Core\Http\Request;
use EasySwoole\Core\Http\Response;
use think\Db;

/**
 * Class Index
 * @package App\HttpController
 */
class Index extends ViewController
{
    public function __construct(string $actionName, Request $request, Response $response)
    {
        parent::__construct($actionName, $request, $response);
    }
    
    protected function onRequest($action): ?bool
    {
        return parent::onRequest($action); // TODO: Change the autogenerated stub
    }
    
    public function index()
    {
        $sql = "show tables";
        $re = Db::query($sql);
        var_dump($re);
        $assign = array(
            'test'=>1,
            'db'=>$re
        );
        $this->getView()->assign($assign);
        $this->fetch('index');
    
    }

}

在App/Views/Index/Index/建立index.html

代码语言:javascript
复制
test:{$test}<br>

即可使用模板引擎

六:使用$_SESSION,$_GET,$_POST等全局变量

新增baseController控制器,继承ViewController

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2018/7/19
 * Time: 16:21
 */

namespace App\Base;

use EasySwoole\Config;
use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Request;
use EasySwoole\Core\Http\Response;
use EasySwoole\Core\Http\Session\Session;
use think\Template;

class BaseController extends ViewController
{
    use Tool;
    protected $config;
    protected $session;

    public function __construct(string $actionName, Request $request, Response $response)
    {
        parent::__construct($actionName, $request, $response);
        $this->header();
    }

    public function defineVariable()
    {


    }

    protected function onRequest($action): ?bool
    {
        return parent::onRequest($action); // TODO: Change the autogenerated stub
    }

    public function init($actionName, $request, $response)
    {
        $class_name                         = static::class;
        $array                              = explode('\\', $class_name);
        $GLOBALS['base']['MODULE_NAME']     = $array[2];
        $GLOBALS['base']['CONTROLLER_NAME'] = $array[3];
        $GLOBALS['base']['ACTION_NAME']     = $actionName;

        $this->session($request, $response)->sessionStart();
        $_SESSION['user'] = $this->session($request, $response)->get('user');//session

        $_GET     = $request->getQueryParams();
        $_POST    = $request->getRequestParam();
        $_REQUEST = $request->getRequestParam();
        $_COOKIE  = $request->getCookieParams();

        $this->defineVariable();
        parent::init($actionName, $request, $response); // TODO: Change the autogenerated stub
        $this->getView()->assign('session', $_SESSION['user']);
    }

    public function header()
    {
        $this->response()->withHeader('Content-type', 'text/html;charset=utf-8');
    }

    /**
     * 首页方法
     * @author : evalor <master@evalor.cn>
     */
    public function index()
    {
        return false;
    }


    function session($request = null, $response = null): Session  //重写session方法
    {
        $request == null && $request = $this->request();
        $response == null && $response = $this->response();
        if ($this->session == null) {
            $this->session = new Session($request, $response);
        }
        return $this->session;
    }
}

在EasySwooleEvent.php  afterAction中,进行销毁全局变量

代码语言:javascript
复制
public static function afterAction(Request $request, Response $response): void
{
    unset($GLOBALS);
    unset($_GET);
    unset($_POST);
    unset($_SESSION);
    unset($_COOKIE);
}

七:使用fastRoute自定义路由

1:在App/HttpController下新增文件Router.php

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2018/7/24
 * Time: 15:20
 */

namespace App\HttpController;


use EasySwoole\Config;
use EasySwoole\Core\Http\Request;
use EasySwoole\Core\Http\Response;
use FastRoute\RouteCollector;

class Router extends \EasySwoole\Core\Http\AbstractInterface\Router
{
    
    function register(RouteCollector $routeCollector)
    {
        $configs = Config::getInstance()->getConf('web.FAST_ROUTE_CONFIG');//直接取web配置文件的配置
        foreach ($configs as $config){
            $routeCollector->addRoute($config[0],$config[1],$config[2]);
        }
        
    }
}

web.config配置

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 2018/7/24
 * Time: 9:03
 */
return array(
    'FAST_ROUTE_CONFIG' => array(
        array('GET','/test', '/Index/Index/test'),//本人在HttpController目录下分了模块层,所以是Index/Index
    ),
);

访问xx.cn/test 即可重写到/Index/Index/test方法

八:现成源码

本人组装好轮子的源码已经开源,可以直接下载开撸,代码与教程有一点点的不同,有问题可以加qq群633921431提问

https://github.com/tioncico/easyES

本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-07-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一:使用nginx代理easyswoole  http
  • 二:使用nginx访问静态文件
  • 三:引入自定义配置
    • 1: 在App/Config/下增加database.php,web.php,config.php
      • 2:在全局配置文件EasySwooleEvent.php中参照以下代码:
      • 四:使用ThinkORM
        • 1:安装
          • 2:创建配置文件
            • 3:在EasySwooleEvent.php参照以下代码
              • 4:查询实例
                • 5:Model
                • 五:使用tp模板引擎
                  • 1:安装
                    • 2:建立view基类
                      • 控制器继承ViewController类
                        • 在App/Views/Index/Index/建立index.html
                        • 六:使用$_SESSION,$_GET,$_POST等全局变量
                        • 七:使用fastRoute自定义路由
                          • 1:在App/HttpController下新增文件Router.php
                            • web.config配置
                            • 八:现成源码
                            相关产品与服务
                            数据库
                            云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
                            领券
                            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档