使用easyswoole進行開發web網站

easyswoole作爲swoole入門最簡單的框架,其框架的定義就是適合大衆php,更好的利用swoole擴展進行開發,

 

以下是本人使用easyswoole,看easyswoole文檔總結出來的,關於easyswoole開發普通web網站的一些步驟

 

看下文之前,請先安裝easyswoole框架

 

本文適用於es2.x版本,現在es3.x版本已經完全穩定,文檔,demo完善,可移步www.easyswoole.com

查看文檔以及demo

也可查看最新文章:easyswoole快速實現一個網站的api接口程序

 

 

一:使用nginx代理easyswoole  http

nginx增加配置:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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中參照以下代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<?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:調用方法:

1

2

    // 獲得配置

    $Conf = Config::getInstance()->getConf(文件名);

 

 

四:使用ThinkORM

1:安裝

1

composer require topthink/think-orm

2:創建配置文件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<?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參照以下代碼

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<?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查詢一樣

1

2

3

4

5

6

7

8

9

10

11

Db::table('user')

    ->data(['name'=>'thinkphp','email'=>'[email protected]'])

    ->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

1

2

3

4

5

6

7

8

9

10

11

namespace App\Model;

 

use App\Base\Tool;

use EasySwoole\Core\AbstractInterface\Singleton;

use think\Db;

use think\Model;

 

Class user extends Model

{

   

}

即可使用model

1

2

3

4

5

6

 use App\Model\User;

 function index(){

    $member = User::get(1);

    $member->username = 'test';

    $member->save();

    $this->response()->write('Ok');}

 

五:使用tp模板引擎

 

1:安裝

1

composer require topthink/think-template

2:建立view基類

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

<?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 <[email protected]>

 * @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 <[email protected]>

     */

    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類

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

<?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

1

test:{$test}<br>

即可使用模板引擎

 

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

新增baseController控制器,繼承ViewController
 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

<?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 <[email protected]>

     */

    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中,進行銷燬全局變量

1

2

3

4

5

6

7

8

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<?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配置

1

2

3

4

5

6

7

8

9

10

11

12

<?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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章