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 EasySwooleCoreAbstractInterfaceEventInterface;
use EasySwooleCoreUtilityFile;
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' => 'thinkCollection',
// 数据库类型
'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 EasySwooleCoreAbstractInterfaceEventInterface;
use EasySwooleCoreUtilityFile;
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
只需要继承thinkModel类,在App/Model/下新增User.php
代码语言:javascript复制namespace AppModel;
use AppBaseTool;
use EasySwooleCoreAbstractInterfaceSingleton;
use thinkDb;
use thinkModel;
Class user extends Model
{
}
即可使用model
代码语言:javascript复制 use AppModelUser;
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 AppBase;
use EasySwooleConfig;
use EasySwooleCoreHttpAbstractInterfaceController;
use EasySwooleCoreHttpRequest;
use EasySwooleCoreHttpResponse;
use EasySwooleCoreHttpSessionSession;
use thinkTemplate;
/**
* 视图控制器
* 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 AppHttpControllerIndex;
use AppBaseHomeBaseController;
use AppBaseViewController;
use EasySwooleCoreHttpRequest;
use EasySwooleCoreHttpResponse;
use thinkDb;
/**
* Class Index
* @package AppHttpController
*/
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 AppBase;
use EasySwooleConfig;
use EasySwooleCoreHttpAbstractInterfaceController;
use EasySwooleCoreHttpRequest;
use EasySwooleCoreHttpResponse;
use EasySwooleCoreHttpSessionSession;
use thinkTemplate;
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 AppHttpController;
use EasySwooleConfig;
use EasySwooleCoreHttpRequest;
use EasySwooleCoreHttpResponse;
use FastRouteRouteCollector;
class Router extends EasySwooleCoreHttpAbstractInterfaceRouter
{
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
- 上一篇: php实现img转ASCII编码图片
- 下一篇: 关于实现登陆踢下线功能的思维图