本文目的

使用composer创建yii2的advance工程,并安装配置常用工具

我觉得我已经写的非常详细了,如果真的哪里有疏漏,通知我。

关于yii2两个模板的区别,在初识yii2里面有写,这里主要说相关工具的安装以及配置。

安装完成之后的效果:http://yii.moozik.cn


环境要求

PHP 5.4.0 或以上,且打开了SSL扩展,且已经加入的环境变量

本文主要讨论windows下的开发,linux并未刻意介绍,但是区别并不大,如果你有linux基础一样可以通过本文的步骤安装yii2。

建议事项

建议使用phpstudy搭建环境。

不建议使用系统自带记事本。

推荐使用RapidEEPortable来管理环境变量。


全部步骤

对配置文件的修改如果不确定添加到哪里,请拉到页面最下面查看我配置好的main.php等文件。

composer

参考:

简介 | Composer 中文文档 | Composer 中文网

PHP 开发者该知道的 5 个 Composer 小技巧

下载安装composer

composer有多种安装方法

命令行安装(不推荐):

  php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
  php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
  php composer-setup.php
  php -r "unlink('composer-setup.php');"

安装完成之后会出现一个composer.phar文件,可以使用php composer.phar打开。
不推荐这样安装的原因是他只安装了一个主文件,没有bat文件帮助方便的启动composer。
如果你已经有了composer.phar那么你可以选择自己创建辅助工具。
给linux使用的启动脚本:

  #!/bin/sh
  dir=$(cd "${0%/*}" && pwd)
  if [[ $dir == /cygdrive/* && $(which php) == /cygdrive/* ]]; then    
      # cygwin paths for windows PHP must be translated
      dir=$(cygpath -m "$dir");    
  fi
  php "${dir}/composer.phar" "$@"

给windows使用的启动脚本:

  @echo OFF
  :: in case DelayedExpansion is on and a path contains ! 
  setlocal DISABLEDELAYEDEXPANSION
  php "%~dp0composer.phar" %*

如果不使用上面这两个启动脚本的话要使用php composer.phar来打开composer,创建之后只需要composer就可以打开了,更重要的是,大多数教程中写的安装命令都是第二种方式。

exe安装包安装:
windows的用户推荐使用的方式:composer下载页面

使用exe安装包方式安装完成之后,会得到三个文件:
一个windows启动脚本,一个linux启动脚本,一个composer.phar主文件。

仅仅有这些文件还不够,你需要保证脚本文件在环境变量中,并与composer.phar在同一个目录,可以创建一个composer的安装目录来放这些文件,使用exe安装的默认路径为C:\ProgramData\ComposerSetup\bin,保证你的路径是在环境变量中的,这时候我们就装好composer了。

中国镜像与github token

执行下面这条命令来启用快速的中国镜像,不执行这条命令会耗费大量时间在安装上。

composer config -g repo.packagist composer https://packagist.phpcomposer.com

在使用composer过程中,他可能会打印下面的提示:

  Could not fetch https://api.github.com/repos/RobinHerbots/jquery.inputmask/contents/bower.json?ref=03e65a2d28159e885e18acee9cae53ac6318372b, please create a GitHub OAuth token to go over the API rate limit
  Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+on+localhost.localdomain+2015-05-19+1651
  to retrieve a token. It will be stored in "/home/vagrant/.composer/auth.json" for future use by Composer.
  Token (hidden): 

这时候登陆你的github,打开https://github.com/settings/tokens,点击右上角的Generate new token按钮,复制出现的token,粘贴到cmd中点击回车,粘贴到cmd中将会看不到回显,直接回车就可以了,之后他就会继续工作。

两个composer使用的目录,除非你是专家,否则不要轻易修改

  #配置文件以及一些php文件
  C:\Users\用户名\AppData\Roaming\Composer
  #已经安装过的所有安装包,以及命令log
  C:\Users\用户名\AppData\Local\Composer

安装yii2

参考:

下载 - Yii Framework 中文社区

安装 Yii(Installing Yii) - 入门(Getting Started)

命令行 | Composer 中文文档 | Composer 中文网

composer安装yii2

我们只推荐使用composer方式安装,当你使用过几次就会发现他很省心。

命令解释:

  • --prefer-dist意思是,不从github克隆源代码,这样效率会高一些,对于稳定版本 composer 将默认使用 dist 方式。
  • yiisoft/yii2-app-advanced是软件包的代码。
  • yii2-advance是我打算创建的项目文件夹,你可以另写。
  #运行下面的命令来安装Composer Asset插件:
  composer global require "fxp/composer-asset-plugin:^1.2.0"
  #安装高级的应用程序模板
  composer create-project --prefer-dist yiisoft/yii2-app-advanced yii2-advance

执行上面的命令,下面是完整的执行回显(我把其中换行的地方复原了):

  C:\phpstudy\www>composer global require "fxp/composer-asset-plugin:^1.2.0"
  Changed current directory to C:/Users/wangyusen/AppData/Roaming/Composer
  ./composer.json has been updated
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update
  Writing lock file
  Generating autoload files
  C:\phpstudy\www>composer create-project --prefer-dist yiisoft/yii2-app-advanced yii2-advance
  Installing yiisoft/yii2-app-advanced (2.0.12)
    - Installing yiisoft/yii2-app-advanced (2.0.12): Downloading (100%)
  Created project in yii2-advance
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Package operations: 62 installs, 0 updates, 0 removals
    - Installing yiisoft/yii2-composer (2.0.5): Downloading (100%)
    - Installing swiftmailer/swiftmailer (v5.4.8): Downloading (100%)
    - Installing bower-asset/jquery (2.2.4): Loading from cache
    - Installing bower-asset/yii2-pjax (v2.0.6): Loading from cache
    - Installing bower-asset/punycode (v1.3.2): Loading from cache
    - Installing cebe/markdown (1.1.1): Downloading (100%)
    - Installing ezyang/htmlpurifier (v4.9.3): Downloading (100%)
    - Installing bower-asset/jquery.inputmask (3.3.7): Loading from cache
    - Installing yiisoft/yii2 (2.0.12): Downloading (100%)
    - Installing yiisoft/yii2-swiftmailer (2.0.7): Downloading (100%)
    - Installing bower-asset/bootstrap (v3.3.7): Loading from cache
    - Installing yiisoft/yii2-bootstrap (2.0.6): Downloading (100%)
    - Installing yiisoft/yii2-debug (2.0.9): Downloading (100%)
    - Installing bower-asset/typeahead.js (v0.11.1): Loading from cache
    - Installing phpspec/php-diff (v1.1.0): Downloading (100%)
    - Installing yiisoft/yii2-gii (2.0.5): Downloading (100%)
    - Installing fzaninotto/faker (v1.6.0): Downloading (100%)
    - Installing yiisoft/yii2-faker (2.0.3): Downloading (100%)
    - Installing psr/log (1.0.2): Downloading (100%)
    - Installing symfony/debug (v3.3.2): Downloading (100%)
    - Installing symfony/polyfill-mbstring (v1.4.0): Downloading (100%)
    - Installing symfony/console (v3.3.2): Downloading (100%)
    - Installing stecman/symfony-console-completion (0.7.0): Downloading (connecting...)Downloading (100%)
    - Installing sebastian/diff (1.4.3): Downloading (100%)
    - Installing sebastian/recursion-context (3.0.0): Downloading (100%)
    - Installing sebastian/exporter (3.1.0): Downloading (100%)
    - Installing sebastian/comparator (2.0.0): Downloading (100%)
    - Installing behat/gherkin (v4.4.5): Downloading (100%)
    - Installing symfony/dom-crawler (v3.3.2): Downloading (100%)
    - Installing symfony/css-selector (v3.3.2): Downloading (100%)
    - Installing symfony/browser-kit (v3.3.2): Downloading (100%)
    - Installing symfony/yaml (v3.3.2): Downloading (100%)
    - Installing symfony/event-dispatcher (v3.3.2): Downloading (100%)
    - Installing symfony/finder (v3.3.2): Downloading (100%)
    - Installing psr/http-message (1.0.1): Downloading (100%)
    - Installing guzzlehttp/psr7 (1.4.2): Downloading (100%)
    - Installing doctrine/instantiator (1.0.5): Downloading (100%)
    - Installing phpunit/php-text-template (1.2.1): Downloading (100%)
    - Installing phpunit/phpunit-mock-objects (4.0.1): Downloading (connecting...)Downloading (100%)
    - Installing theseer/tokenizer (1.1.0): Downloading (100%)
    - Installing sebastian/version (2.0.1): Downloading (100%)
    - Installing sebastian/environment (3.0.4): Downloading (100%)
    - Installing sebastian/code-unit-reverse-lookup (1.0.1): Downloading (connecting...)Downloading (100%)
    - Installing phpunit/php-token-stream (1.4.11): Downloading (100%)
    - Installing phpunit/php-file-iterator (1.4.2): Downloading (100%)
    - Installing phpunit/php-code-coverage (5.2.1): Downloading (100%)
    - Installing sebastian/resource-operations (1.0.0): Downloading (connecting...)Downloading (100%)
    - Installing sebastian/object-reflector (1.1.1): Downloading (100%)
    - Installing sebastian/object-enumerator (3.0.2): Downloading (100%)
    - Installing sebastian/global-state (2.0.0): Downloading (100%)
    - Installing phpunit/php-timer (1.0.9): Downloading (100%)
    - Installing webmozart/assert (1.2.0): Downloading (100%)
    - Installing phpdocumentor/reflection-common (1.0): Downloading (connecting...)Downloading (100%)
    - Installing phpdocumentor/type-resolver (0.2.1): Downloading (100%)
    - Installing phpdocumentor/reflection-docblock (3.1.1): Downloading (connecting...)Downloading (100%)
    - Installing phpspec/prophecy (v1.7.0): Downloading (100%)
    - Installing phar-io/version (1.0.1): Downloading (100%)
    - Installing phar-io/manifest (1.0.1): Downloading (100%)
    - Installing myclabs/deep-copy (1.6.1): Downloading (100%)
    - Installing phpunit/phpunit (6.2.2): Downloading (100%)
    - Installing codeception/base (2.3.3): Downloading (100%)
    - Installing codeception/verify (0.3.3): Downloading (100%)
  symfony/console suggests installing symfony/filesystem ()
  symfony/console suggests installing symfony/process ()
  symfony/browser-kit suggests installing symfony/process ()
  symfony/event-dispatcher suggests installing symfony/dependency-injection ()
  symfony/event-dispatcher suggests installing symfony/http-kernel ()
  phpunit/phpunit-mock-objects suggests installing ext-soap (*)
  phpunit/php-code-coverage suggests installing ext-xdebug (^2.5.3)
  sebastian/global-state suggests installing ext-uopz (*)
  phpunit/phpunit suggests installing phpunit/php-invoker (^1.1)
  phpunit/phpunit suggests installing ext-xdebug (*)
  codeception/base suggests installing codeception/specify (BDD-style code blocks)
  
  codeception/base suggests installing flow/jsonpath (For using JSONPath in REST module)
  codeception/base suggests installing phpseclib/phpseclib (for SFTP option in FTP Module)
  codeception/base suggests installing league/factory-muffin (For DataFactory module)
  codeception/base suggests installing league/factory-muffin-faker (For Faker support in DataFactory module)
  codeception/base suggests installing symfony/phpunit-bridge (For phpunit-bridgesupport)
  Writing lock file
  Generating autoload files

init初始化

进入yii2-advance目录,执行init初始化yii2,首先键入0设置当前环境为Development,然后键入yes确定操作。可以看到创建了一系列的local文件,以及最重要的yii命令行程序。下面是完整的首次执行回显。

  C:\phpstudy\www\yii2-advance>init
  Yii Application Initialization Tool v1.0
  
  Which environment do you want the application to be initialized in?
  
    [0] Development
    [1] Production
  
    Your choice [0-1, or "q" to quit] 0
  
    Initialize the application under 'Development' environment? [yes|no] yes
  
    Start initialization ...
  
     generate backend/config/main-local.php
     generate backend/config/params-local.php
     generate backend/config/test-local.php
     generate backend/web/index-test.php
     generate backend/web/index.php
     generate backend/web/robots.txt
     generate common/config/main-local.php
     generate common/config/params-local.php
     generate common/config/test-local.php
     generate console/config/main-local.php
     generate console/config/params-local.php
     generate frontend/config/main-local.php
     generate frontend/config/params-local.php
     generate frontend/config/test-local.php
     generate frontend/web/index-test.php
     generate frontend/web/index.php
     generate frontend/web/robots.txt
     generate yii
     generate yii_test
     generate yii_test.bat
     generate cookie validation key in backend/config/main-local.php
     generate cookie validation key in frontend/config/main-local.php
        chmod 0777 backend/runtime
        chmod 0777 backend/web/assets
        chmod 0777 frontend/runtime
        chmod 0777 frontend/web/assets
        chmod 0755 yii
        chmod 0755 yii_test
  
    ... initialization completed.

配置vhost和hosts

最后一步,将yii2-advance虚拟成一个站点,如果你使用的是apache服务器,那么找到你apache中的vhosts.conf文件,在其中追加如下代码,如果你使用的是phpstudy那么直接打开站点域名设置就可以设置站点了。
记得把其中路径换成你的真实路径。

  <VirtualHost *:80>
      DocumentRoot "C:\phpstudy\www\yii2-advance\frontend\web"
      ServerName www.yii2.com
      ServerAlias yii2.com
    <Directory "C:\phpstudy\www\yii2-advance\frontend\web">
        Options FollowSymLinks ExecCGI
        AllowOverride All
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>
  </VirtualHost>

打开c:\windows\System32\drivers\etc\hosts,追加一行localhost www.yii2.com,保存。

打开yii2-advance目录中的composer.json,里面展示了当前包含的所有包,至此yii2-advance安装完成,重启服务器,浏览器中打开www.yii2.com可以看到欢迎页面。

yii2基本配置

参考:

路由 -- Yii2 url地址美化与重写

url美化

入口文件get参数结构

我们可以打开yii2的about示例页面http://www.yii2.com/index.php?r=site/about

默认情况下,一个方法就是这样访问的,他的结构为http://www.yii2.com/入口php?r=控制器/方法名

这个about方法的位置为:

frontend\controllers\SiteController.php文件中的actionAbout方法

这个方法调用了frontend\views\site\about.php视图文件显示页面。

开启url美化

现在我们开启url美化看看会发生什么不一样的情况。

将下面的代码加入到frontend\config\main.php数组中的components数组,与session处于同一层级,文件中本来是有这段代码的,但是默认注释掉了,把注释删掉就可以了。

  'urlManager' => [
      'enablePrettyUrl' => true,
      'showScriptName' => false,
      'rules' => [
      ],
  ],
同样是在这个文件,这里我们顺带添加上多语言支持'language' => 'zh-CN',,将这一行添加到最外层,和components同一层级。

加入完成之后我们可以尝试打开http://www.yii2.com/index.php/site/about链接

发现一样可以打开about页面,开启url美化之后省略了get参数名,url看起来更整洁了。下面我们进一步美化将index.php隐藏起来。

请确认LoadModule rewrite_module modules/mod_rewrite.so已经存在于你的apache配置文件,并且已经启用。

将下面的代码创建为frontend\web\.htaccess,apache服务器会读取这个文件获取rewrite规则。

有些电脑可能会出现不能在\frontend\web\目录中直接创建.htaccess的情况,这时候直接在编辑器新建文件编辑,保存到这个目录中就可以了。
  Options +FollowSymLinks
  IndexIgnore */*
  RewriteEngine on

  # if a directory or a file exists, use it directly
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  # otherwise forward it to index.php
  RewriteRule . index.php

尝试打开http://www.yii2.com/site/about链接,发现一样可以打开about页面。
http://www.yii2.com/index.php/site/about仍然可以访问about页面。

原理

现在我们知道apache的mod_rewrite.so扩展实现的效果为,将/site/about地址在内部映射为/index.php/site/about,也就是说我们访问的是/site/about,但是apache却将/index.php/site/about发送给了php,php将这个地址发送给yii解析,yii中我们开启了url美化已经支持这种写法,所以我们又打开了about页面。

小TIPS

另外说一点,在url重写的过程中,进行了一个文件是否存在的判断,/site/about如果有一个site目录,目录中有一个about文件,那么会直接访问这个文件,如果文件不存在才会去重写url,这个是一个需要注意的地方,不注意的话以后文件多了可能会发生一些极端情况。

邮箱和数据库配置

配置邮箱
由于我们配置的是邮箱和数据库,所以选择配置到common目录中,因为这样整个项目都可以使用相同的邮箱和数据库配置。

因为我的留言提醒一直很正常,所以就用了blog的邮箱。需要注意的是,只能使用默认的25端口,因为使用465端口需要开启其他组件,我尝试把端口改成465然后把下面的注释去掉,发现不能发信,页面一直卡死。

添加到common\config\main-local.php数组中的components数组,他本身是有mailer的配置的,注释了或者删掉。

  //配置邮箱
  'mailer' => [
      'class' => 'yii\swiftmailer\Mailer',
      'viewPath' => '@app/mailer',
      'useFileTransport' => false,//这句一定有,false发送邮件,true只是生成邮件在runtime文件夹下,不发邮件
      'transport' => [
          'class' => 'Swift_SmtpTransport',
          'host' => 'smtp.moozik.cn',//每种邮箱的host配置不一样
          'username' => 'hello@moozik.cn',
          'password' => 'HXlSowt5jhr5bpt0',
          'port' => '25',
          /* 'encryption' => 'tls', */
      ],
  ],

修改frontend\config\params.php文件

修改成

  <?php
  return [
      'adminEmail' => 'hello@moozik.cn',
  ];

具体这个邮件是在哪里会用到暂时不太清楚。

我们将frontend\controllers\SiteController.php中的actionAbout()方法修改成如下

  public function actionAbout()
  {
      Yii::$app->mailer->compose()
          ->setFrom('hello@moozik.cn')
          ->setTo('936629633@qq.com')
          ->setSubject('Message subject')
          ->setTextBody('Plain text content')
          ->setHtmlBody('<b>傻蛋</b>')
          ->send();
      return $this->render('about');
  }

再次打开about页面,会发现有一点点卡顿,再打开qq邮箱,发现收到邮件了。
微信截图_20170629130744.png

配置数据库

修改common\config\main-local.php中的数据库配置,如下,同时在本地创建yii2advance数据库

'db' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2advance',
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8',
],

小TIPS
如果你用的是阿里云的企业邮箱,重复发信可能会导致退信,因为阿里有专门的邮件推送服务,阿里的企业邮箱会过滤看起来像垃圾邮件的邮件。

不要试我的密码,上面代码中的邮箱密码是另外生成的( ﹁ ﹁ ) ~→

安装配置yii2-user插件

安装

进入yii2-advance目录,执行composer require dektrium/yii2-user
以下是完整命令回显:

C:\phpstudy\www\yii2-advance>composer require dektrium/yii2-user
Using version ^0.9.12 for dektrium/yii2-user
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 3 installs, 0 updates, 0 removals
  - Installing yiisoft/yii2-httpclient (2.0.4): Downloading (100%)
  - Installing yiisoft/yii2-authclient (2.1.3): Downloading (100%)
  - Installing dektrium/yii2-user (0.9.12): Downloading (100%)
yiisoft/yii2-authclient suggests installing spomky-labs/jose (required for JWS,JWT or JWK related flows like OpenIDConnect)
Writing lock file
Generating autoload files

配置

frontend\config\main.phpcomponents中的user注释掉
在文件中数组的最外层,components的同一层级添加如下代码:

    'modules' => [
        'user' => [
            'class' => 'dektrium\user\Module',
        ],
    ],

数据库迁移

现在程序和配置已经安装好了,还差数据库没有导入,为了准备好我们下面安装的admin,需要对当前的文件做一点修改。
打开vendor\dektrium\yii2-user\migrations\m140209_132017_init.php
将其中创建user表的程序段,添加两行,如下

'password_reset_token' => $this->string(256)->Null(), //add for admin
'status'               => $this->integer()->notNull(10)->defaultValue(10), //add for admin

添加完成后创建user表的方法变成如下的样式。

$this->createTable('{{%user}}', [
    'id'                   => $this->primaryKey(),
    'username'             => $this->string(25)->notNull(),
    'email'                => $this->string(255)->notNull(),
    'password_hash'        => $this->string(60)->notNull(),
    'auth_key'             => $this->string(32)->notNull(),
    'confirmation_token'   => $this->string(32)->null(),
    'confirmation_sent_at' => $this->integer()->null(),
    'confirmed_at'         => $this->integer()->null(),
    'unconfirmed_email'    => $this->string(255)->null(),
    'recovery_token'       => $this->string(32)->null(),
    'recovery_sent_at'     => $this->integer()->null(),
    'blocked_at'           => $this->integer()->null(),
    'registered_from'      => $this->integer()->null(),
    'logged_in_from'       => $this->integer()->null(),
    'logged_in_at'         => $this->integer()->null(),
    'created_at'           => $this->integer()->notNull(),
    'updated_at'           => $this->integer()->notNull(),
    
    'password_reset_token' => $this->string(256)->Null(), //add for admin
    'status'               => $this->integer()->notNull(10)->defaultValue(10), //add for admin
], $this->tableOptions);

修改完成之后保存代码,打开cmd,定位到yii2-advance目录,使用yii的工具执行数据库迁移,执行下面代码

php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations

完整的回显我就不贴了,太乱了,如果执行成功,cmd中最后两行为

12 migrations were applied.

Migrated up successfully.

这时查看数据库,发现多了5个表,除了migration是系统创建的,剩下的都是刚才执行的命令创建的。

注册账号

这时我们访问http://www.yii2.com/user/login可以看到刚刚安装的dektrium/yii2-user中的登陆界面。

微信截图_20170629155031.png

而访问http://www.yii2.com/site/login看到的是项目自带的登陆界面。

微信截图_20170629155050.png

导航上的signup和login按钮依然是自带的注册和登陆,测试的时候需要自己手打地址。
我们在浏览器打开http://www.yii2.com/user/register进入注册账号页面注册账号。

微信截图_20170629160400.png

注册之后会给你发送一封邮件,如下。


您好,

Your account on My Application has been created.

为了完成您的注册,请点击下面的链接.

http://www.yii2.com/user/confirm/1/Ak0kaVyPQd18cyQrE6t5v1bV4X472vE9

如果不能直接打开,请将以上网址粘贴到到浏览器打开.

温馨提示:如果您错误地收到这封电子邮件,只需要删除它.

© My Application 2017.

点击里面的链接验证邮箱,跳转回网站中,显示Thank you, registration is now complete.

dektrium/yii2-user的安装就完成了。

安装配置yii2-admin插件

参考:
yii2-admin 插件使用简要教程
搭建 rabc 后台系列教程(二)—— 安装 AdminLTE和 yii2-admin

安装

打开cmd定位到yii2-advance目录中,执行

composer require mdmsoft/yii2-admin "~2.0"

cmd完整回显为

C:\phpstudy\www\yii2-advance>composer require mdmsoft/yii2-admin "~2.0"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing mdmsoft/yii2-admin (2.7): Downloading (100%)
Writing lock file
Generating autoload files

配置

与上面安装yii2-user类似,打开frontend\config\main.phpmodules添加如下配置

//加载admin
'admin' => [
    'class' => 'mdm\admin\Module',
],

components中添加

//权限控制
'authManager' => [
    'class' => 'yii\rbac\DbManager',
],

打开vendor\mdmsoft\yii2-admin\migrations\m160312_050000_create_user.php文件
将其中up()方法中的所有代码注释,因为刚刚安装的yii2-user已经创建了user表,并且我们将yii2-admin需要的两个字段也添加到了表中,所以在安装yii2-admin的时候,我们已经不需要创建user表了。

打开cmd,在yii2-advance目录中执行:

php yii migrate --migrationPath=@mdm/admin/migrations

完整回显为:

C:\phpstudy\www\yii2-advance>php yii migrate --migrationPath=@mdm/admin/migrations
Yii Migration Tool (based on Yii v2.0.12)

Total 2 new migrations to be applied:
        m140602_111327_create_menu_table
        m160312_050000_create_user

Apply the above migrations? (yes|no) [no]:yes
*** applying m140602_111327_create_menu_table
    > create table {{%menu}} ... done (time: 0.009s)
*** applied m140602_111327_create_menu_table (time: 0.035s)

*** applying m160312_050000_create_user
*** applied m160312_050000_create_user (time: 0.009s)


2 migrations were applied.

Migrated up successfully.

打开console\config\main.php
在其中添加上下面的代码,至于为什么要添加,是因为添加了才不报错,执行完数据库迁移就删掉就好了。

//权限控制
'authManager' => [
    'class' => 'yii\rbac\DbManager',
],

继续在项目目录执行数据库迁移命令

php yii migrate --migrationPath=@yii/rbac/migrations

完整回显为

C:\phpstudy\www\yii2-advance>php yii migrate --migrationPath=@yii/rbac/migrations
Yii Migration Tool (based on Yii v2.0.12)

Total 1 new migration to be applied:
        m140506_102106_rbac_init

Apply the above migration? (yes|no) [no]:yes
*** applying m140506_102106_rbac_init
    > create table {{%auth_rule}} ... done (time: 0.010s)
    > create table {{%auth_item}} ... done (time: 0.008s)
    > create index idx-auth_item-type on {{%auth_item}} (type) ... done (time: 0.018s)
    > create table {{%auth_item_child}} ... done (time: 0.010s)
    > create table {{%auth_assignment}} ... done (time: 0.007s)
*** applied m140506_102106_rbac_init (time: 0.082s)


1 migration was applied.

Migrated up successfully.

这时候打开数据库看一眼,如果一切顺利,你配置的数据里应该有刚好10张表。

这时打开http://www.yii2.com/admin就可以看到yii2-admin的功能列表和介绍。
yii2-admin安装配置完成。

安装配置yii2-adminlte

参考:
搭建 rabc 后台系列教程(二)—— 安装 AdminLTE和 yii2-admin
yii2-adminlte-asset / yii2-admin 安装配置

yii2-adminlte安装

在yii2-advance目录中执行:

composer require dmstr/yii2-adminlte-asset "2.*"

完整回显:

C:\phpstudy\www\yii2-advance>composer require dmstr/yii2-adminlte-asset "2.*"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
  - Installing fortawesome/font-awesome (v4.7.0): Downloading (100%)
  - Installing rmrevin/yii2-fontawesome (2.17.1): Downloading (100%)
  - Installing almasaeed2010/adminlte (v2.3.11): Downloading (100%)
  - Installing cebe/yii2-gravatar (1.1): Downloading (100%)
  - Installing dmstr/yii2-adminlte-asset (2.4.2): Downloading (100%)
Writing lock file
Generating autoload files

yii2-adminlte配置

打开vendor\dmstr\yii2-adminlte-asset\example-views\yiisoft\yii2-app目录
复制其中的两个文件夹,创建文件夹frontend\themes\adminlte,将那两个文件夹粘贴进去。

这么做的主要原因是方便管理,如果之后有新增的主题,直接在themes文件夹中再创建文件夹就可以了。

frontend\config\main.php中的components添加如下

//设置主题
'view' => [
    'theme' => [
        'pathMap' => [
            //刚才配置的路径
            '@app/views' => '@frontend/themes/adminlte'
        ],
    ],
],
//设置主题
//全部主题去vendor\almasaeed2010\adminlte\dist\css\skins目录找对应css文件的名字
'assetManager' => [
    'bundles' => [
        'dmstr\web\AdminLteAsset' => [
            //使用绿色主题
            'skin' => 'skin-green',
        ],
    ],
],

打开frontend\themes\adminlte\layouts\main.php
将其中body头标签注释,修改为如下

<!--    <body class="hold-transition skin-blue sidebar-mini">-->
    <body class="<?= \dmstr\helpers\AdminLteHelper::skinClass() ?>">

现在刷新主页http://www.yii2.com/,可以看到已经换上了新皮肤。

给登陆增加验证码

修改下面两个文件前,记得备份一下,修改vendor里面的代码,最好备份一下。

vendor\dektrium\yii2-user\models\LoginForm.php中添加

//添加在class中
public $captcha;

//添加在rules()中
$rules[] = ['captcha', 'required'];
$rules[] = ['captcha', 'captcha'];

vendor\dektrium\yii2-user\views\security\login.php中添加

//add for 验证码
use yii\captcha\Captcha;

//查找下面两行数据,按下面修改
// 'enableAjaxValidation' => true,
// 'enableClientValidation' => false,
'enableAjaxValidation' => false,
'enableClientValidation' => true,

//将下面的代码放到你想要显示验证码的地方
<?= $form->field($model, 'captcha')->widget(Captcha::className(), [
    'captchaAction' => ['/site/captcha']
])->label('验证码') ?>

访问http://www.yii2.com/site/logout退出登陆,不退出登陆无法进入登陆页面。
打开http://www.yii2.com/user/login,可以看到我们配置了验证码登陆。

微信截图_20170629190552.png

尝试不输入验证码或者验证码输入错误,发现无法登陆,验证配置完成。

附录

配置完成之后项目中部分文件的全文。

frontend\config\main.php

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'name' => '项目名字', // 默认没有,可以自行添加,这个名字会出现在adminlte左侧顶端
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    //多语言
    'language' => 'zh-CN',
    //额外安装的模块
    'modules' => [
        //加载user
        'user' => [
            'class' => 'dektrium\user\Module',
        ],
        //加载admin
        'admin' => [
            'class' => 'mdm\admin\Module',
        ],
    ],
    //游客权限
    'as access' => [
        'class' => 'mdm\admin\components\AccessControl',
        'allowActions' => [
            'site/*',
            'admin/*',
            'user/*',
        ]
    ],
    'components' => [
        //开启url美化
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        //权限控制
        'authManager' => [
            'class' => 'yii\rbac\DbManager',
        ],
        //设置主题
        'view' => [
            'theme' => [
                'pathMap' => [
                    '@app/views' => '@frontend/themes/adminlte'
                ],
            ],
        ],
        //设置主题
        'assetManager' => [
            'bundles' => [
                'dmstr\web\AdminLteAsset' => [
                    'skin' => 'skin-green',
                ],
            ],
        ],
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
//        'user' => [
//            'identityClass' => 'common\models\User',
//            'enableAutoLogin' => true,
//            'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
//        ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend', // 这个地方设置的是cookie和session中的key
        ],
        'log' => [//不需要log可以关掉
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ],
    'params' => $params,
];

common\config\main-local.php

<?php
return [
    'components' => [
        //配置数据库
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2advance',
            'username' => 'root',
            'password' => 'root',
            'charset' => 'utf8',
        ],
        //配置邮箱
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@app/mailer',
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.moozik.cn',
                'username' => 'hello@moozik.cn',
                'password' => 'password',
                'port' => '25',
//                'encryption' => 'tls',
            ],
        ],
    ],
];

composer.json
该文件包含了项目的依赖和其它的一些元数据。
参考:
基本用法 | Composer 中文文档
按道理来说你把下面的文件放到你的yii2目录中,执行composer update就可以更新所有包了,我没测试过,不保证成功

{
    "name": "yiisoft/yii2-app-advanced",
    "description": "Yii 2 Advanced Project Template",
    "keywords": ["yii2", "framework", "advanced", "project template"],
    "homepage": "http://www.yiiframework.com/",
    "type": "project",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/yii2/issues?state=open",
        "forum": "http://www.yiiframework.com/forum/",
        "wiki": "http://www.yiiframework.com/wiki/",
        "irc": "irc://irc.freenode.net/yii",
        "source": "https://github.com/yiisoft/yii2"
    },
    "minimum-stability": "stable",
    "require": {
        "php": ">=5.4.0",
        "yiisoft/yii2": "~2.0.6",
        "yiisoft/yii2-bootstrap": "~2.0.0",
        "yiisoft/yii2-swiftmailer": "~2.0.0",
        "dektrium/yii2-user": "^0.9.12",
        "mdmsoft/yii2-admin": "~2.0",
        "dmstr/yii2-adminlte-asset": "2.*"
    },
    "require-dev": {
        "yiisoft/yii2-debug": "~2.0.0",
        "yiisoft/yii2-gii": "~2.0.0",
        "yiisoft/yii2-faker": "~2.0.0",

        "codeception/base": "^2.2.3",
        "codeception/verify": "~0.3.1"
    },
    "config": {
        "process-timeout": 1800,
        "fxp-asset":{
            "installer-paths": {
                "npm-asset-library": "vendor/npm",
                "bower-asset-library": "vendor/bower"
            }
        }
    }
}
最后修改:2021 年 01 月 12 日
如果觉得我的文章对你有用,请随意赞赏