没有不值得去解决的问题,也没有不值得去学习的技术!

基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),新建api目录、配置和环境、测试、Vagrant等的支持

新建 api 目录、配置和环境、测试、Vagrant 等的支持。

Yii2 Advanced 实战系列:RESTful API + RPC 服务 + 国际化 + 日志与测试

新建 api 目录、配置和环境、测试、Vagrant 等的支持。

(1) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),新建api目录、配置和环境、测试、Vagrant等的支持

(2) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),实现模型分层:数据层、逻辑层,明确公共目录、应用、模块的继承、引用关系

在 Postman 中,GET http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,200响应,message为简体中文

(3) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),实现 RESTful Web 服务,支持国际化(动态地设置目标语言,默认为简体中文)

运行测试,获取详细的输出,可看到一步一步的行为报告,符合预期

(4) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),在 api 的 tests 目录中准备用户相关操作的一些自动化测试的样例(API 测试),确保应用程序在改变或增加新的功能时不会影响现有的功能

在 Postman 中,GET http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/logs?filter[level]=4&filter[category][like]=api\behaviors\RequestLogBehavior&filter[prefix][like]=app-api&filter[log_time][gte]=1528090828&filter[log_time][lte]=1529564924.6648 ,200响应,空数组已经被自动转换为空对象,以保证字段格式的统一,GET http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/logs/3

(5) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),调整默认字符集为:utf8mb4,接口响应格式的调整,空数组自动转换为空对象,在接口应用中收集请求日志消息(1个请求对应1条日志消息)至数据库,且实现日志功能的相应接口:日志列表(设置数据过滤器以启用筛选器处理)、日志详情

在开发环境中,执行数据库迁移命令失败:1071 Specified key was too long; max key length is 767 bytes

(6) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),调整默认字符集为:utf8mb4,接口响应格式的调整,空数组自动转换为空对象,在接口应用中收集请求日志消息(1个请求对应1条日志消息)至数据库,且实现日志功能的相应接口:日志列表(设置数据过滤器以启用筛选器处理)、日志详情(二)

浏览 user 表数据,status、updated_at 已经更新

(7) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),实现 ActiveRecord 的软删除,生成 ActiveQuery,自定义查询类

执行数据库迁移命令,查看数据库表 user 结构,符合预期

(8) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),实现 ActiveRecord 的软删除,生成 ActiveQuery,自定义查询类(二)

在 Postman 中 POST 请求,http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/users ,输入格式:application/json

(9) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),application/x-www-form-urlencoded 和 multipart/form-data 输入格式,默认支持,新增 application/json 输入格式的支持

打开 Windows PowerShell,执行 init 命令并选择 dev 作为环境,api应用所需环境配置文件自动生成

(10) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建远程过程调用应用(实现基于 Hprose 2.0 for PHP 的 RPC 服务端),新建 rpc 目录、配置和环境、测试、Vagrant等的支持

出现以上原因是因为 Windows 下 nginx php 环境,不支持并发的原因,当同时访问多个域名,并且同时指向你本地服务的时候,就不支持并发了。nginx.conf 里面 对不同 server 修改 fastcgi_pass 的端口号,启动多个 php-cgi。

(11) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建远程过程调用应用(实现基于 Hprose 2.0 for PHP 的 RPC 服务端),在 rpc 目录中实现 页面 的相应 RPC 服务,且在 api 目录中的 API 实现 RPC 客户端

执行数据库迁移,查看表结构,基于 Gii 重新生成模型文件

(12) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,UUID 的实现

由于日志消息是存储于 MySQL 的 log 表中,在生产环境中,累积了大量的数据,log 表的数据长度已经达到 数百 GB ,因此,决定基于控制台命令行实现日志消息的定时删除,开发环境的 log 表的数据长度为 14.64 GB

(13) 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,日志消息的自动定时删除

1、创建一个新的仓库,shuijingwan/yii2-app-advanced,如图1
Yii 2高级项目模板,模板包括四个层:接口(实现 RESTful 风格的 Web Service 服务的 API),前端,后端和控制台,每个都是单独的Yii应用程序。

创建一个新的仓库,shuijingwan/yii2-app-advanced
图1

2、创建仓库成功,如图2

创建仓库成功
图2

3、使用以下命令安装应用程序:yiisoft/yii2-app-advanced,如图3

使用以下命令安装应用程序:yiisoft/yii2-app-advanced
图3

composer self-update
composer global require "fxp/composer-asset-plugin"
composer create-project --prefer-dist yiisoft/yii2-app-advanced github-shuijingwan-yii2-app-advanced


4、在命令行上创建一个新的仓库,推送现有的仓库至shuijingwan/yii2-app-advanced,基于第2步骤,如图4

在命令行上创建一个新的仓库,推送现有的仓库至shuijingwan/yii2-app-advanced,基于第2步骤
图4

git init
git add .
git commit -m "安装 yiisoft/yii2-app-advanced 后,全部提交。"
git remote add origin https://github.com/shuijingwan/yii2-app-advanced.git
git push -u origin master


5、打开:https://github.com/shuijingwan/yii2-app-advanced ,仓库已经推送成功,如图5

打开:https://github.com/shuijingwan/yii2-app-advanced ,仓库已经推送成功
图5

6、打开 Windows PowerShell,执行 init 命令并选择 dev 作为环境,如图6

打开 Windows PowerShell,执行 init 命令并选择 dev 作为环境
图6

.\init
0
yes


7、更改主机文件以将域指向您的服务器,配置 C:\Windows\System32\drivers\etc\hosts 文件,如图7

更改主机文件以将域指向您的服务器,配置 C:\Windows\System32\drivers\etc\hosts 文件
图7

# github-shuijingwan-yii2-app-advanced
127.0.0.1 github-shuijingwan-yii2-app-advanced.localhost www.github-shuijingwan-yii2-app-advanced.localhost backend.github-shuijingwan-yii2-app-advanced.localhost api.github-shuijingwan-yii2-app-advanced.localhost


8、基于 Nginx 配置 Web 服务器,配置虚拟主机:www、backend,api 暂缓配置,编辑 C:\nginx-1.10.1\conf\vhosts\github-shuijingwan-yii2-app-advanced.conf


## FRONTEND ##
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

    server_name www.github-shuijingwan-yii2-app-advanced.localhost;
    root        E:/wwwroot/github-shuijingwan-yii2-app-advanced/frontend/web;
    index       index.php;

    access_log  logs/www.github-shuijingwan-yii2-app-advanced.localhost.access.log;
    error_log   logs/www.github-shuijingwan-yii2-app-advanced.localhost.error.log;

	location / {
		# Redirect everything that isn't a real file to index.php
		try_files $uri $uri/ /index.php$is_args$args;
	}

	# uncomment to avoid processing of calls to non-existing static files by Yii
	#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
	#    try_files $uri =404;
	#}
	#error_page 404 /404.html;

	# deny accessing php files for the /assets directory
	location ~ ^/assets/.*\.php$ {
		deny all;
	}

	location ~ \.php$ {
		include fastcgi_params;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		fastcgi_pass 127.0.0.1:9000;
		#fastcgi_pass unix:/var/run/php5-fpm.sock;
		try_files $uri =404;
	}

	location ~* /\. {
		deny all;
	}
}

## BACKEND ##
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

    server_name backend.github-shuijingwan-yii2-app-advanced.localhost;
    root        E:/wwwroot/github-shuijingwan-yii2-app-advanced/backend/web;
    index       index.php;

    access_log  logs/backend.github-shuijingwan-yii2-app-advanced.localhost.access.log;
    error_log   logs/backend.github-shuijingwan-yii2-app-advanced.localhost.error.log;

	location / {
		# Redirect everything that isn't a real file to index.php
		try_files $uri $uri/ /index.php$is_args$args;
	}

	# uncomment to avoid processing of calls to non-existing static files by Yii
	#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
	#    try_files $uri =404;
	#}
	#error_page 404 /404.html;

	# deny accessing php files for the /assets directory
	location ~ ^/assets/.*\.php$ {
		deny all;
	}

	location ~ \.php$ {
		include fastcgi_params;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		fastcgi_pass 127.0.0.1:9000;
		#fastcgi_pass unix:/var/run/php5-fpm.sock;
		try_files $uri =404;
	}

	location ~* /\. {
		deny all;
	}
}

## MISC ##

### WWW Redirect ###
server {
    listen       80;
    server_name  github-shuijingwan-yii2-app-advanced.localhost;
    return       301 http://www.github-shuijingwan-yii2-app-advanced.localhost$request_uri;
}



9、检查当前 PHP 环境是否满足 Yii 最基本需求,复制 /requirements.php 到 /frontend/web/requirements.php,然后通过浏览器访问 URL http://www.github-shuijingwan-yii2-app-advanced.localhost/requirements.php ,如图8

检查当前 PHP 环境是否满足 Yii 最基本需求,复制 /requirements.php 到 /frontend/web/requirements.php,然后通过浏览器访问 URL http://www.github-shuijingwan-yii2-app-advanced.localhost/requirements.php
图8

$frameworkPath = dirname(__FILE__) . '/../../vendor/yiisoft/yii2';


10、创建一个新的数据库(g-s-yii2-app-advanced),并相应地调整 /common/config/main-local.php 中的 components[‘db’] 配置,字符集为utf8mb4。


CREATE USER 'g-s-yii2-app-advanced'@'%' IDENTIFIED WITH mysql_native_password AS '***';GRANT USAGE ON *.* TO 'g-s-yii2-app-advanced'@'%' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;CREATE DATABASE IF NOT EXISTS `g-s-yii2-app-advanced`;GRANT ALL PRIVILEGES ON `g-s-yii2-app-advanced`.* TO 'g-s-yii2-app-advanced'@'%';



        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=g-s-yii2-app-advanced',
            'username' => 'g-s-yii2-app-advanced',
            'password' => 'IADO0x7uK4UpaRRM',
            'charset' => 'utf8mb4',
        ],


11、执行迁移命令,如图9

执行迁移命令
图9

.\yii migrate
yes


12、查看数据库,排序规则为:utf8mb4_unicode_ci,如图10

查看数据库,排序规则为:utf8mb4_unicode_ci
图10

13、创建测试数据库(g-s-yii2-app-advanced-test),并相应地调整 /common/config/test-local.php 中的 components[‘db’] 配置,字符集为utf8mb4。


CREATE USER 'g-s-yii2-app-advanced-test'@'%' IDENTIFIED WITH mysql_native_password AS '***';GRANT USAGE ON *.* TO 'g-s-yii2-app-advanced-test'@'%' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;CREATE DATABASE IF NOT EXISTS `g-s-yii2-app-advanced-test`;GRANT ALL PRIVILEGES ON `g-s-yii2-app-advanced-test`.* TO 'g-s-yii2-app-advanced-test'@'%';



            'db' => [
                'dsn' => 'mysql:host=localhost;dbname=g-s-yii2-app-advanced-test',
                'username' => 'g-s-yii2-app-advanced-test',
                'password' => '9dIXzEvrGN9akpcO',
                'charset' => 'utf8mb4',
            ]


14、执行迁移命令,报错:Exception ‘yii\base\UnknownPropertyException’ with message ‘Setting unknown property: yii\console\Request::cookieValidat
ionKey’ in E:\wwwroot\github-shuijingwan-yii2-app-advanced\vendor\yiisoft\yii2\base\Component.php:209,如图11

执行迁移命令,报错:Exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\console\Request::cookieValidat ionKey' in E:\wwwroot\github-shuijingwan-yii2-app-advanced\vendor\yiisoft\yii2\base\Component.php:209
图11

./yii_test migrate


15、由于控制台应用程序使用不同的请求组件,因此编辑 \common\config\test.php,注释 request 组件(在 Web 应用程序中需取消注释),如图12

由于控制台应用程序使用不同的请求组件,因此编辑 \common\config\test.php,注释 request 组件(在 Web 应用程序中需取消注释)
图12

    'components' => [
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'common\models\User',
        ],
        /*
        'request' => [
            'cookieValidationKey' => 'test',
        ],
        */
    ],


16、执行迁移命令、构建测试套件,然后运行所有的样例测试,如图13
注:执行迁移命令(./yii_test migrate)后,需取消注释 request 组件,否则报错:

执行迁移命令、构建测试套件,然后运行所有的样例测试
图13

 Test  ..\common\tests\unit\models\LoginFormTest.php:testLoginCorrect

  [yii\base\InvalidConfigException] yii\web\Request::cookieValidationKey must be configured with a secret key.



./yii_test migrate
vendor/bin/codecept build
vendor/bin/codecept run


17、查看测试数据库,排序规则为:utf8mb4_unicode_ci,如图14

查看测试数据库,排序规则为:utf8mb4_unicode_ci
图14

18、添加接口应用程序(api),复制 frontend 至 api, environments/dev/frontend 至 environments/dev/api 以及 environments/prod/frontend 至 environments/prod/api,如图15

添加接口应用程序(api),复制 frontend 至 api, environments/dev/frontend 至 environments/dev/api 以及 environments/prod/frontend 至 environments/prod/api
图15

19、删除目录 \api\runtime\debug 下的所有文件,在目录 /api 中调整命名空间和路径以 api 开头(替换 frontend 为 api),如图16

删除目录 \api\runtime\debug 下的所有文件,在目录 /api 中调整命名空间和路径以 api 开头(替换 frontend 为 api)
图16

20、在 common\config\bootstrap.php 中添加 Yii::setAlias(‘api’, dirname(dirname(__DIR__)) . ‘/api’);,如图17

在 common\config\bootstrap.php 中添加 Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');
图17

21、编辑environments/index.php,搜索此文件有6处frontend,则相应复制6份,替换为api,如图18

编辑environments/index.php,搜索此文件有6处frontend,则相应复制6份,替换为api
图18

22、\vagrant\nginx\app.conf,新增虚拟主机 api

\vagrant\nginx\app.conf


server {
   charset utf-8;
   client_max_body_size 128M;
   sendfile off;

   listen 80; ## listen for ipv4
   #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

   server_name y2aa-frontend.test;
   root        /app/frontend/web/;
   index       index.php;

   access_log  /app/vagrant/nginx/log/frontend-access.log;
   error_log   /app/vagrant/nginx/log/frontend-error.log;

   location / {
       # Redirect everything that isn't a real file to index.php
       try_files $uri $uri/ /index.php$is_args$args;
   }

   # uncomment to avoid processing of calls to non-existing static files by Yii
   #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
   #    try_files $uri =404;
   #}
   #error_page 404 /404.html;

   location ~ \.php$ {
       include fastcgi_params;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       #fastcgi_pass   127.0.0.1:9000;
       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
       try_files $uri =404;
   }

   location ~ /\.(ht|svn|git) {
       deny all;
   }
}

server {
   charset utf-8;
   client_max_body_size 128M;
   sendfile off;

   listen 80; ## listen for ipv4
   #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

   server_name y2aa-backend.test;
   root        /app/backend/web/;
   index       index.php;

   access_log  /app/vagrant/nginx/log/backend-access.log;
   error_log   /app/vagrant/nginx/log/backend-error.log;

   location / {
       # Redirect everything that isn't a real file to index.php
       try_files $uri $uri/ /index.php$is_args$args;
   }

   # uncomment to avoid processing of calls to non-existing static files by Yii
   #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
   #    try_files $uri =404;
   #}
   #error_page 404 /404.html;

   location ~ \.php$ {
       include fastcgi_params;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       #fastcgi_pass   127.0.0.1:9000;
       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
       try_files $uri =404;
   }

   location ~ /\.(ht|svn|git) {
       deny all;
   }
}

server {
   charset utf-8;
   client_max_body_size 128M;
   sendfile off;

   listen 80; ## listen for ipv4
   #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

   server_name y2aa-api.test;
   root        /app/api/web/;
   index       index.php;

   access_log  /app/vagrant/nginx/log/api-access.log;
   error_log   /app/vagrant/nginx/log/api-error.log;

   location / {
       # Redirect everything that isn't a real file to index.php
       try_files $uri $uri/ /index.php$is_args$args;
   }

   # uncomment to avoid processing of calls to non-existing static files by Yii
   #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
   #    try_files $uri =404;
   #}
   #error_page 404 /404.html;

   location ~ \.php$ {
       include fastcgi_params;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       #fastcgi_pass   127.0.0.1:9000;
       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
       try_files $uri =404;
   }

   location ~ /\.(ht|svn|git) {
       deny all;
   }
}



23、编辑 \vagrant\nginx\log\.gitignore,配置api的日志文件为忽略


# nginx logs
backend-access.log
backend-error.log
frontend-access.log
frontend-error.log
api-access.log
api-error.log


24、编辑 \Vagrantfile,新增 api 相关的配置


require 'yaml'
require 'fileutils'

required_plugins = %w( vagrant-hostmanager vagrant-vbguest )
required_plugins.each do |plugin|
    exec "vagrant plugin install #{plugin}" unless Vagrant.has_plugin? plugin
end

domains = {
  frontend: 'y2aa-frontend.test',
  backend:  'y2aa-backend.test',
  api:      'y2aa-api.test',
}

config = {
  local: './vagrant/config/vagrant-local.yml',
  example: './vagrant/config/vagrant-local.example.yml'
}

# copy config from example if local config not exists
FileUtils.cp config[:example], config[:local] unless File.exist?(config[:local])
# read config
options = YAML.load_file config[:local]

# check github token
if options['github_token'].nil? || options['github_token'].to_s.length != 40
  puts "You must place REAL GitHub token into configuration:\n/yii2-app-advanced/vagrant/config/vagrant-local.yml"
  exit
end

# vagrant configurate
Vagrant.configure(2) do |config|
  # select the box
  config.vm.box = 'bento/ubuntu-16.04'

  # should we ask about box updates?
  config.vm.box_check_update = options['box_check_update']

  config.vm.provider 'virtualbox' do |vb|
    # machine cpus count
    vb.cpus = options['cpus']
    # machine memory size
    vb.memory = options['memory']
    # machine name (for VirtualBox UI)
    vb.name = options['machine_name']
  end

  # machine name (for vagrant console)
  config.vm.define options['machine_name']

  # machine name (for guest machine console)
  config.vm.hostname = options['machine_name']

  # network settings
  config.vm.network 'private_network', ip: options['ip']

  # sync: folder 'yii2-app-advanced' (host machine) -> folder '/app' (guest machine)
  config.vm.synced_folder './', '/app', owner: 'vagrant', group: 'vagrant'

  # disable folder '/vagrant' (guest machine)
  config.vm.synced_folder '.', '/vagrant', disabled: true

  # hosts settings (host machine)
  config.vm.provision :hostmanager
  config.hostmanager.enabled            = true
  config.hostmanager.manage_host        = true
  config.hostmanager.ignore_private_ip  = false
  config.hostmanager.include_offline    = true
  config.hostmanager.aliases            = domains.values

  # provisioners
  config.vm.provision 'shell', path: './vagrant/provision/once-as-root.sh', args: [options['timezone']]
  config.vm.provision 'shell', path: './vagrant/provision/once-as-vagrant.sh', args: [options['github_token']], privileged: false
  config.vm.provision 'shell', path: './vagrant/provision/always-as-root.sh', run: 'always'

  # post-install message (vagrant console)
  config.vm.post_up_message = "Frontend URL: http://#{domains[:frontend]}\nBackend URL: http://#{domains[:backend]}\nApi URL: http://#{domains[:api]}"
end



25、基于 Nginx 配置 Web 服务器,配置虚拟主机:www、backend、api,编辑 C:\nginx-1.10.1\conf\vhosts\github-shuijingwan-yii2-app-advanced.conf


## FRONTEND ##
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

    server_name www.github-shuijingwan-yii2-app-advanced.localhost;
    root        E:/wwwroot/github-shuijingwan-yii2-app-advanced/frontend/web;
    index       index.php;

    access_log  logs/www.github-shuijingwan-yii2-app-advanced.localhost.access.log;
    error_log   logs/www.github-shuijingwan-yii2-app-advanced.localhost.error.log;

	location / {
		# Redirect everything that isn't a real file to index.php
		try_files $uri $uri/ /index.php$is_args$args;
	}

	# uncomment to avoid processing of calls to non-existing static files by Yii
	#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
	#    try_files $uri =404;
	#}
	#error_page 404 /404.html;

	# deny accessing php files for the /assets directory
	location ~ ^/assets/.*\.php$ {
		deny all;
	}

	location ~ \.php$ {
		include fastcgi_params;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		fastcgi_pass 127.0.0.1:9000;
		#fastcgi_pass unix:/var/run/php5-fpm.sock;
		try_files $uri =404;
	}

	location ~* /\. {
		deny all;
	}
}

## BACKEND ##
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

    server_name backend.github-shuijingwan-yii2-app-advanced.localhost;
    root        E:/wwwroot/github-shuijingwan-yii2-app-advanced/backend/web;
    index       index.php;

    access_log  logs/backend.github-shuijingwan-yii2-app-advanced.localhost.access.log;
    error_log   logs/backend.github-shuijingwan-yii2-app-advanced.localhost.error.log;

	location / {
		# Redirect everything that isn't a real file to index.php
		try_files $uri $uri/ /index.php$is_args$args;
	}

	# uncomment to avoid processing of calls to non-existing static files by Yii
	#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
	#    try_files $uri =404;
	#}
	#error_page 404 /404.html;

	# deny accessing php files for the /assets directory
	location ~ ^/assets/.*\.php$ {
		deny all;
	}

	location ~ \.php$ {
		include fastcgi_params;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		fastcgi_pass 127.0.0.1:9000;
		#fastcgi_pass unix:/var/run/php5-fpm.sock;
		try_files $uri =404;
	}

	location ~* /\. {
		deny all;
	}
}

## API ##
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80; ## listen for ipv4
    #listen [::]:80 default_server ipv6only=on; ## listen for ipv6

    server_name api.github-shuijingwan-yii2-app-advanced.localhost;
    root        E:/wwwroot/github-shuijingwan-yii2-app-advanced/api/web;
    index       index.php;

    access_log  logs/api.github-shuijingwan-yii2-app-advanced.localhost.access.log;
    error_log   logs/api.github-shuijingwan-yii2-app-advanced.localhost.error.log;

	location / {
		# Redirect everything that isn't a real file to index.php
		try_files $uri $uri/ /index.php$is_args$args;
	}

	# uncomment to avoid processing of calls to non-existing static files by Yii
	#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
	#    try_files $uri =404;
	#}
	#error_page 404 /404.html;

	# deny accessing php files for the /assets directory
	location ~ ^/assets/.*\.php$ {
		deny all;
	}

	location ~ \.php$ {
		include fastcgi_params;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		fastcgi_pass 127.0.0.1:9000;
		#fastcgi_pass unix:/var/run/php5-fpm.sock;
		try_files $uri =404;
	}

	location ~* /\. {
		deny all;
	}
}

## MISC ##

### WWW Redirect ###
server {
    listen       80;
    server_name  github-shuijingwan-yii2-app-advanced.localhost;
    return       301 http://www.github-shuijingwan-yii2-app-advanced.localhost$request_uri;
}



26、打开 Windows PowerShell,执行 init 命令并选择 dev 作为环境,api应用所需环境配置文件自动生成,如图19

打开 Windows PowerShell,执行 init 命令并选择 dev 作为环境,api应用所需环境配置文件自动生成
图19

.\init
0
yes
Yes
Yes
Yes
Yes
Yes


27、打开:http://api.github-shuijingwan-yii2-app-advanced.localhost/ ,符合预期,如图20

打开:http://api.github-shuijingwan-yii2-app-advanced.localhost/ ,符合预期
图20

28、编辑 codeception.yml 配置包含所有应用程序的测试,如图21

编辑 codeception.yml 配置包含所有应用程序的测试
图21

# global codeception file to run tests from all apps
include:
    - common
    - frontend
    - backend
    - api
paths:
    log: console/runtime/logs
settings:
    colors: true


29、运行所有的样例测试,包含 api,如图22

运行所有的样例测试,包含 api
图22

vendor/bin/codecept run


30、编辑 README.md,在目录结构中新增 api



    
        
    
    Yii 2 Advanced Project Template
    


Yii 2 Advanced Project Template is a skeleton [Yii 2](http://www.yiiframework.com/) application best for
developing complex Web applications with multiple tiers.

The template includes three tiers: front end, back end, and console, each of which
is a separate Yii application.

The template is designed to work in a team development environment. It supports
deploying the application in different environments.

Documentation is at [docs/guide/README.md](docs/guide/README.md).

[![Latest Stable Version](https://img.shields.io/packagist/v/yiisoft/yii2-app-advanced.svg)](https://packagist.org/packages/yiisoft/yii2-app-advanced)
[![Total Downloads](https://img.shields.io/packagist/dt/yiisoft/yii2-app-advanced.svg)](https://packagist.org/packages/yiisoft/yii2-app-advanced)
[![Build Status](https://travis-ci.org/yiisoft/yii2-app-advanced.svg?branch=master)](https://travis-ci.org/yiisoft/yii2-app-advanced)

DIRECTORY STRUCTURE
-------------------

```
common
    config/              contains shared configurations
    mail/                contains view files for e-mails
    models/              contains model classes used in both api and backend and frontend
    tests/               contains tests for common classes    
console
    config/              contains console configurations
    controllers/         contains console controllers (commands)
    migrations/          contains database migrations
    models/              contains console-specific model classes
    runtime/             contains files generated during runtime
backend
    assets/              contains application assets such as JavaScript and CSS
    config/              contains backend configurations
    controllers/         contains Web controller classes
    models/              contains backend-specific model classes
    runtime/             contains files generated during runtime
    tests/               contains tests for backend application    
    views/               contains view files for the Web application
    web/                 contains the entry script and Web resources
frontend
    assets/              contains application assets such as JavaScript and CSS
    config/              contains frontend configurations
    controllers/         contains Web controller classes
    models/              contains frontend-specific model classes
    runtime/             contains files generated during runtime
    tests/               contains tests for frontend application
    views/               contains view files for the Web application
    web/                 contains the entry script and Web resources
    widgets/             contains frontend widgets
api
    assets/              contains application assets such as JavaScript and CSS
    config/              contains api configurations
    controllers/         contains Web controller classes
    models/              contains api-specific model classes
    runtime/             contains files generated during runtime
    tests/               contains tests for api application
    views/               contains view files for the Web application
    web/                 contains the entry script and Web resources
    widgets/             contains api widgets
vendor/                  contains dependent 3rd-party packages
environments/            contains environment-based overrides
```



31、测试使用Vagrant安装,是否支持 api,参考网址:https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide-zh-CN/start-installation.md ,使用Vagrant安装(Windows 用户手册)

32、进入 /vagrant/config 文件夹,重命名 vagrant-local.example.yml 为 vagrant-local.yml(建议复制),将GitHub个人API令牌放置到 vagrant-local.yml,如图23

进入 /vagrant/config 文件夹,重命名 vagrant-local.example.yml 为 vagrant-local.yml(建议复制),将GitHub个人API令牌放置到 vagrant-local.yml
图23

33、添加如下代码到 hosts 文件


# github-shuijingwan-yii2-app-advanced Vagrant
192.168.83.137 y2aa-frontend.test y2aa-backend.test y2aa-api.test


34、打开Windows PowerShell,切换路径至项目根目录,并且执行如下命令(需要翻墙,可能需要执行多次),期间有报错,参考第15步骤处理,如图24、图25

打开Windows PowerShell,切换路径至项目根目录,并且执行如下命令
图24
期间有报错,参考第15步骤处理
图25

vagrant plugin install vagrant-hostmanager
vagrant up


35、等待完成后,在浏览器中访问如下URL即可,符合预期,如图26
frontend: http://y2aa-frontend.test
backend: http://y2aa-backend.test
api: http://y2aa-api.test

等待完成后,在浏览器中访问如下URL即可,符合预期
图26

36、还原第32步骤所做的修改,且编辑 \vagrant\config\.gitignore


# local configuration
vagrant-local.yml


基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),实现模型分层:数据层、逻辑层,明确公共目录、应用、模块的继承、引用关系

PHP / Yii2 老项目维护与长期技术支持

如果你的 Yii2 项目已经上线,但遇到原开发离职、Bug 长期无人修复、接口不稳定、性能下降、代码难以接手等问题,可以联系我做一次远程技术排查。

适合以下情况:
✅ Yii2 老项目无人维护
✅ 后台管理系统 Bug 修复
✅ RESTful API 接口排查
✅ 小功能迭代与历史代码接手
✅ MySQL / Redis / Nginx 性能问题
✅ 长期远程兼职维护

可先从一次小问题开始:
✅ 线上报错排查
✅ 接口异常分析
✅ 慢查询与性能瓶颈定位
✅ 代码结构初步评估
✅ 部署环境与日志检查

如需咨询,请联系我,并注明:Yii2 维护咨询

联系方式:
Telegram:@shuijingwan
微信:13980074657
邮箱:shuijingwanwq@gmail.com

评论

一条对“基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用(实现 RESTful 风格的 Web Service 服务的 API),新建api目录、配置和环境、测试、Vagrant等的支持”的回复

  1. […] 基于 yiisoft/yii2-app-advanced,在 GitHub 上新建仓库 yii2-app-advanced,新建接口应用… […]

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理