原创 2016年06月02日 09:28:09




安装 composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

yii 插件
composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application

/*****cd into yii-application dir*****/

yum -y install mysql-server
yum -y install httpd
yum -y remove php*
yum -y install php54w* --skip-broken

layout "main" defined in yii\base\Application.php

"user" component defined in yii\web\Application.php, pointing to class defined in yii\web\User.php

class "User" in yii\web\User.php include member "$identityClass", which is an object of class "User" in common\models\User.php, and this class do the authentication work, the former "User" class only maintains user authentication status. Define in frontend/config/main.php:'identityClass' => 'common\models\User'.

Execute "yii migrate --migrationPath=@yii/rbac/migrations"

| Tables_in_yii2advanced |
| auth_assignment        |
| auth_item              |
| auth_item_child        |
| auth_rule              |     
|                        |
| country                |
| migration              |
| user                   |

Yii::$app = $this; in yii\base\Application.php: public function __construct($config = [])

int frontend\views\layouts\main.php:

<?= Breadcrumbs::widget([
     'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>

yii\web\Request.php: get post data via method post()

in frontend\controllers\SiteController.php
public function actionContact()
   $model = new ContactForm();
   if ($model->load(Yii::$app->request->post()) && $model->validate())

in frontend\models\ContactForm.php

public function rules()
    return [
          // name, email, subject and body are required
          [['name', 'email', 'subject', 'body'], 'required'],
          // email has to be a valid email address
          ['email', 'email'],
          // verifyCode needs to be entered correctly
          ['verifyCode', 'captcha'],

in yii\base\Model.php:

public function validate($attributeNames = null, $clearErrors = true)
      $scenarios = $this->scenarios();
      $scenario = $this->getScenario();
      if (!isset($scenarios[$scenario])) {
          throw new InvalidParamException("Unknown scenario: $scenario");
      if ($attributeNames === null) {
           $attributeNames = $this->activeAttributes();
      foreach ($this->getActiveValidators() as $validator) {      
          $validator->validateAttributes($this, $attributeNames);

Validattors available:

boolean: yii\validators\BooleanValidator
captcha: yii\captcha\CaptchaValidator
compare: yii\validators\CompareValidator
date: yii\validators\DateValidator
default: yii\validators\DefaultValueValidator
double: yii\validators\NumberValidator
each: yii\validators\EachValidator
email: yii\validators\EmailValidator
exist: yii\validators\ExistValidator
file: yii\validators\FileValidator
filter: yii\validators\FilterValidator
image: yii\validators\ImageValidator
in: yii\validators\RangeValidator
integer: yii\validators\NumberValidator
match: yii\validators\RegularExpressionValidator
required: yii\validators\RequiredValidator
safe: yii\validators\SafeValidator
string: yii\validators\StringValidator
trim: yii\validators\FilterValidator
unique: yii\validators\UniqueValidator
url: yii\validators\UrlValidator
ip: yii\validators\IpValidator

public function behaviors()
     return [
          'access' => [
              'class' => AccessControl::className(),
              'only' => ['logout', 'signup'], 
                    'rules' => [
                       'actions' => ['signup'],
                       'allow' => true,
                       'roles' => ['?'],
                       'actions' => ['logout'],
                       'allow' => true,'
                       'roles' => ['@'],


class AccessControl extends ActionFilter

class ActionFilter extends Behavior

class Behavior extends Object

Behaviors, also known as mixins, allow you to enhance the functionality of an existing component class without needing to change the class's inheritance. Attaching a behavior to a component "injects" the behavior's methods and properties into the component, making those methods and properties accessible as if they were defined in the component class itself. Moreover, a behavior can respond to the events triggered by the component, which allows behaviors to also customize the normal code execution of the component.

 If you look at a Yii-generated site, you’ll see that views/layouts/main.php begins with the DOCTYPE and opening HTML tag, then has the HTML HEAD and all its jazz, then starts the BODY, and finally has the footer material and the closing tags. In the middle of the body of the code, you’ll see this line:

<?php echo $content; ?>

This is a magic line as it pulls in the page-specific content. If the site you’re looking at now used Yii, the value of $content would be all the HTML that makes up this post you’re reading. For a Yii example, when the user is looking at site/login, the SiteController‘s actionLogin() method will be called. That method will render the views/site/login.php View page, pulling that file’s contents into the main layout file at that echo $content location. That’s what’s going on behind the scenes.

So here, then, is the first key concept: if you want to change the general look of your Web site, edit the layout file (views/layouts/main.php). If you were to take your HTML mockup for your site, drop in the echo $content; line at the right place, and save it as views/layout/main.php, you will have created a custom look for your Web app. That is the basic principle and it’s essentially that simple.

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../../common/config/main-local.php'),
    require(__DIR__ . '/../config/main.php'),
    require(__DIR__ . '/../config/main-local.php')

$application = new yii\web\Application($config);

class Application extends \yii\base\Application
  protected function bootstrap()
       $request = $this->getRequest();
       Yii::setAlias('@webroot', dirname($request->getScriptFile()));
       Yii::setAlias('@web', $request->getBaseUrl());


   public function coreComponents()
       return array_merge(parent::coreComponents(), [
          'request' => ['class' => 'yii\web\Request'],  
          'response' => ['class' => 'yii\web\Response'],
          'session' => ['class' => 'yii\web\Session'],
          'user' => ['class' => 'yii\web\User'],
          'errorHandler' => ['class' => 'yii\web\ErrorHandler'],


abstract class Application extends Module
    /*** $config, passed from bootstrap file, new yii\web\Application($config) ***/
    public function __construct($config = [])
        Yii::$app = $this;

        $this->state = self::STATE_BEGIN;


    public function preInit(&$config)
        // merge core components with custom components
        foreach ($this->coreComponents() as $id => $component) {
            if (!isset($config['components'][$id])) {
               $config['components'][$id] = $component;
            elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
                $config['components'][$id]['class'] = $component['class'];

    public function init()
        $this->state = self::STATE_INIT;

    public function coreComponents() 
        return [
           'log' => ['class' => 'yii\log\Dispatcher'],
           'view' => ['class' => 'yii\web\View'],
           'formatter' => ['class' => 'yii\i18n\Formatter'],
           'i18n' => ['class' => 'yii\i18n\I18N'],
           'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
           'urlManager' => ['class' => 'yii\web\UrlManager'],
           'assetManager' => ['class' => 'yii\web\AssetManager'],
           'security' => ['class' => 'yii\base\Security'],

class Component extends Object

class Object implements Configurable
     public function __construct($config = [])
        if (!empty($config)) {
           Yii::configure($this, $config);
        $this->init();  // call to yii\base\Application.php

A service locator is an object that knows how to provide all sorts of services (or components) that an application might need. Within a service locator, each component exists as only a single instance, uniquely identified by an ID. You use the ID to retrieve a component from the service locator.

In Yii, a service locator is simply an instance of yii\di\ServiceLocator or a child class.

The most commonly used service locator in Yii is the application object, which can be accessed through \Yii::$app. The services it provides are called application components, such as the request, response, and urlManager components. You may configure these components, or even replace them with your own implementations, easily through functionality provided by the service locator.

class ServiceLocator extends Component

class Module extends ServiceLocator

class Module extends \yii\base\Module implements BootstrapInterface

abstract class Application extends Module

class Application extends \yii\base\Application



public $allowedIPs = ['', '::1', '192.168.0.*']; // check log to see which IP was blocked
                                                          // then add it to allowed list


2015-12-16 09:20:18 [][-][ts64s8bnd2159nlp2gspf6r880][warning][yii\debug\Module::checkAccess] Access to debugger is denied due to IP address restriction. The requesting IP address is

First way(Official way): 

In your main.php config file add these two parameters in your log section and you can see log messages at the end of your page or FireBug Console in your browser. do not forget to set necessary parameters in db section.

'components' => array(
        'enableParamLogging' => true,
                    'showInFireBug' => true,

Second way: 

In your code just change the spelling of one of your columns to something incorrect and you will get an error message contains full SQL query in your error page(you should be in YII_DEBUG mode true). something like this: 
(I have changed t.date to t.wrong_date, when you refresh your page, you will see the generated SQL which was executed in your database)

$criteria = new CDbCriteria();
            $criteria->condition = 't.wrong_date BETWEEN "'.$from_date.'"  AND "'.$to_date.'"';
            $criteria->with = array('order');
            $orders = ProductOrder::model()->findAll($criteria);

in the both ways, have YII_DEBUG true in index.php

defined('YII_DEBUG') or define('YII_DEBUG',true);

* Remember transferring to production environment, disabling gii for security sake

Inorder to successfully create RBAC tables, one has to add DbManager to "/var/www/html/yii-application/console/config/main.php"  and "/var/www/html/yii-application/frontend/config/main.php":

 'components' => [
        'log' => [
            'targets' => [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],

      'authManager' => [
            'class' => 'yii\rbac\DbManager',

版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/flyforfreedom2008/article/details/51563780

yii2 strace 追踪,本地文件

13631 16:16:13 execve("/usr/local/php/bin/php", ["/usr/local/php/bin/php", "/www/web/develop/erp2/ba...
  • terry_water
  • terry_water
  • 2016年02月27日 16:23
  • 779


最近组内Web开发用到了Yii2,我也花了一个多星期的时间来稍微研究一下这个框架。本来想把一些心得写成文章,可是时间过去了 很久,有些调用关系我自己现在已经模糊不清,加上长时间没有码字,要成文还需要考...
  • flyforfreedom2008
  • flyforfreedom2008
  • 2016年06月02日 09:28
  • 1856


最近开工了机房收费系统重构版,确实是有点纠结。 因为这一次是完全应用面向对象的思想设计程序。虽然之前学习了很多次面向对象编程,但是到实际应用的时候,还是会感到无从下手。纠结也没用,因为生活还在继续。。...
  • u010028869
  • u010028869
  • 2014年05月07日 17:49
  • 1714


变量交换 >>> a, b = b, a 循环遍历区间元素 >>>for i in range(10): ... print (i)返回的是生成器对象,生成器比列表更加节省内存 带索引位置的循环...
  • u011404495
  • u011404495
  • 2017年03月03日 15:58
  • 431


1.业务容器战略 2.技术两个阶段--对内--解放人力,提高效率,让大家能更多的专注于做决策性和创造性的事物;---对外--提升客户体验--究极目标--订制/个性化---大数据--根据每个客户的属性...
  • hulkcto
  • hulkcto
  • 2016年08月02日 14:41
  • 71


1.开发准备 欢迎访问我的个人博客:http://ittiger.cn 在官网上下载最新的Smack开发包,我下载的是smack4.1.4版本的,导入相应的jar包...
  • huyongl1989
  • huyongl1989
  • 2015年10月30日 17:09
  • 2522

Android 5.0 + IDA 6.8 调试经验分享

现在升级快,网上的资料只能做参考。  学到了NDK逆向这一块,昨天为了能让IDA 能动态调试SO,瞎折腾了很久,这里分享一下我的经验。 工具:  IDA pro 6.8  Android ...
  • omnispace
  • omnispace
  • 2016年03月11日 17:03
  • 744


js关闭iframe窗口 top.window.location.reload(top.window.location.href); jquery 事件e 的参数  var a = $...
  • nanshan_hzq
  • nanshan_hzq
  • 2016年02月18日 10:19
  • 403


       一路走来,几个月就这样过去了,阳光有过, 风雨没少,而现在,这一切将告一段落。我要离开这里了,将要有一个新的开始!...
  • lengyue_112
  • lengyue_112
  • 2006年01月05日 17:26
  • 726

搭建ELK(ElasticSearch+Logstash+Kibana)日志分析系统(十四) logstash grok 正则解析日志

摘要 这一节补充一下logstash使用grok正则解析日志Grok 是 Logstash 最重要的插件。通过在filter中使用grok,可以把日志中的关键字匹配出来。grok正则主要有两部分: ...
  • qq_24879495
  • qq_24879495
  • 2017年09月16日 10:46
  • 592