手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜Qcloud , 注册 | 登陆
浏览模式: 标准 | 列表Tag:yii2

Yii2 without Bower

 Yii2项目中如何移除Bower库?方法很简单,除了移除fxp插件外,就是利用composer的provide属性

» 阅读全文

Tags: yii2, composer, bower, fxp

Yii2的主从数据库设置

 在yii1的时候,主从数据库的支持没有那么方便,只能写上多个DB的components,然后在AR的getDB中返回相应的db。这样也可以用来对付主从数据库

Yii2则已经解决这个问题,直接在代码中进行处理即可:
PHP代码
  1. 'db' =>[  
  2.      'class' => 'yii\db\Connection',  
  3.   
  4.     // 配置主服务器  
  5.     'dsn' => 'dsn for master server',  
  6.     'username' => 'master',  
  7.     'password' => '',  
  8.     'charset' => 'utf8',  
  9.     'tablePrefix' => 'php_',//默认为空  
  10.   
  11.     // 配置从服务器  
  12.     'slaveConfig' => [  
  13.         'username' => 'slave',  
  14.         'password' => '',  
  15.         'charset' => 'utf8',  
  16.       'tablePrefix' => 'php_',  
  17.         'attributes' => [  
  18.             // use a smaller connection timeout  
  19.             PDO::ATTR_TIMEOUT => 10,  
  20.         ],  
  21.       
  22.     ],  
  23. ];  
是不是感觉超级方便,而不止是这样,你还可以配置从服务器组:
PHP代码
  1. 'db'=>[  
  2.    //...上面是一些标准配置  
  3.     'slaves' => [  
  4.         ['dsn' => 'dsn for slave server 1'],  
  5.         ['dsn' => 'dsn for slave server 2'],  
  6.         ['dsn' => 'dsn for slave server 3'],  
  7.         ['dsn' => 'dsn for slave server 4'],  
  8.     ],   
  9. ]  
更值得称赞的是,主服务器也是多个主服务器的配置就是下面这样,其中字符编码集,表前缀等设置参考上面的。
PHP代码
  1. 'db'=>[  
  2.     // 配置主服务器  
  3.     'masterConfig' => [  
  4.         'username' => 'master',  
  5.         'password' => '',  
  6.         'attributes' => [  
  7.             // use a smaller connection timeout  
  8.             PDO::ATTR_TIMEOUT => 10,  
  9.         ],  
  10.     ],  
  11.   
  12.     // 配置主服务器组  
  13.     'masters' => [  
  14.         ['dsn' => 'dsn for master server 1'],  
  15.         ['dsn' => 'dsn for master server 2'],  
  16.     ],  
  17.     //other ...slaves  
  18. ];  
果然 是轻轻松松啊。
当然 如果你想更轻松的使用,这些,其实就是得用YII2的AR。你就用不着改代码了。。
 
 

Tags: yii2

yiisoft/yii2 2.0.2 requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found

在composer update项目的时候,报了如标题一样的错误,当然这个错误 有一大堆

XML/HTML代码
  1. composer update  
  2. Loading composer repositories with package information  
  3. Updating dependencies (including require-dev)  
  4. Your requirements could not be resolved to an installable set of packages.  
  5.   
  6.   Problem 1  
  7.     - The requested package bower-asset/jquery could not be found in any version, there may be a typo in the package name.  
  8.   Problem 2  
  9.     - Installation request for yiisoft/yii2 dev-master -> satisfiable by yiisoft/yii2[dev-master].  
  10.     - yiisoft/yii2 dev-master requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.  
  11.   Problem 3  
  12.     - yiisoft/yii2 2.0.x-dev requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.  
  13.     - yiisoft/yii2 dev-master requires bower-asset/jquery 2.1.*@stable | 1.11.*@stable -> no matching package found.  
  14.     - Removal request for yiisoft/yii2-imagine == 2.0.9999999.9999999-dev  
  15.     - yiisoft/yii2-imagine 2.0.0 requires yiisoft/yii2 * -> satisfiable by yiisoft/yii2[dev-master, 2.0.x-dev].  
  16.     - yiisoft/yii2-imagine 2.0.0-rc requires yiisoft/yii2 * -> satisfiable by yiisoft/yii2[dev-master, 2.0.x-dev].  
  17.     - yiisoft/yii2-imagine 2.0.1 requires yiisoft/yii2 * -> satisfiable by yiisoft/yii2[dev-master, 2.0.x-dev].  
  18.     - yiisoft/yii2-imagine 2.0.2 requires yiisoft/yii2 * -> satisfiable by yiisoft/yii2[dev-master, 2.0.x-dev].  
  19.     - Removal request for yiisoft/yii2-imagine == 9999999-dev  
  20.     - Installation request for yiisoft/yii2-imagine * -> satisfiable by yiisoft/yii2-imagine[2.0.0, 2.0.0-rc, 2.0.1, 2.0.2, 2.0.x-dev, dev-master].  
  21.   
  22. Potential causes:  
  23.  - A typo in the package name  
  24.  - The package is not available in a stable-enough version according to your minimum-stability setting  
  25.    see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.  
  26.   
  27. Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.  
看上去好纠结,但其实官方有过提示,通过查看:http://www.yiiframework.com/doc-2.0/guide-start-installation.html#installing-via-composer,可知,只要运行:
XML/HTML代码
  1. composer global require "fxp/composer-asset-plugin:1.0.0"  
问题解决。
XML/HTML代码
  1. composer update  
  2. Loading composer repositories with package information  
  3. Updating dependencies (including require-dev)  
  4. Reading bower.json of bower-asset/jquery.inputmask (3.1.47)  
  5. Could not fetch https://api.github.com/repos/RobinHerbots/jquery.inputmask/contents/bower.json?ref=9ff37e85bc2fa2350475c4a7fa60aa20cd211481, enter your GitHub credentials to go over the API rate limit  
  6. The credentials will be swapped for an OAuth token stored in /Users/*******/.composer/auth.json, your password will not be stored  
  7. To revoke access to this token you can visit https://github.com/settings/applications  
  8. Username:********  
  9. Password:********  
  10. Token successfully created  
  11. Reading bower.json of bower-asset/jquery.inputmask (3.1.44)  
  12. 。。。。。。。此处省略500字
 
 
 
 

Tags: yii2

值得收藏的yii2的doc中关于db Query的说明

 
Yii2的DB操作与1有很大的区别。所以下面这段还是值得收藏的
虽然第一句让我很简单,但没关系,大部分内容还是照用的,原文地址来自:https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md
 
为什么就没有cdbcriteria了呢?哎。。。
 

Note: This section is under development.

Yii provides a basic database access layer as described in the Database basics section. The database access layer provides a low-level way to interact with the database. While useful in some situations, it can be tedious and error-prone to write raw SQLs. An alternative approach is to use the Query Builder. The Query Builder provides an object-oriented vehicle for generating queries to be executed.

A typical usage of the query builder looks like the following:

$rows = (new \yii\db\Query())     ->select('id, name')     ->from('user')     ->limit(10)     ->all();  // which is equivalent to the following code:  $query = (new \yii\db\Query())     ->select('id, name')     ->from('user')     ->limit(10);  // Create a command. You can get the actual SQL using $command->sql $command = $query->createCommand();  // Execute the command: $rows = $command->queryAll();

Query Methods

As you can see, [[yii\db\Query]] is the main player that you need to deal with. Behind the scene, Query is actually only responsible for representing various query information. The actual query building logic is done by [[yii\db\QueryBuilder]] when you call the createCommand() method, and the query execution is done by [[yii\db\Command]].

For convenience, [[yii\db\Query]] provides a set of commonly used query methods that will build the query, execute it, and return the result. For example,

  • [[yii\db\Query::all()|all()]]: builds the query, executes it and returns all results as an array.
  • [[yii\db\Query::one()|one()]]: returns the first row of the result.
  • [[yii\db\Query::column()|column()]]: returns the first column of the result.
  • [[yii\db\Query::scalar()|scalar()]]: returns the first column in the first row of the result.
  • [[yii\db\Query::exists()|exists()]]: returns a value indicating whether the query results in anything.
  • [[yii\db\Query::count()|count()]]: returns the result of a COUNT query. Other similar methods include sum($q),average($q)max($q)min($q), which support the so-called aggregational data query. $q parameter is mandatory for these methods and can be either the column name or expression.

Building Query

In the following, we will explain how to build various clauses in a SQL statement. For simplicity, we use $query to represent a [[yii\db\Query]] object.

SELECT

In order to form a basic SELECT query, you need to specify what columns to select and from what table:

$query->select('id, name')     ->from('user');

Select options can be specified as a comma-separated string, as in the above, or as an array. The array syntax is especially useful when forming the selection dynamically:

$query->select(['id', 'name'])     ->from('user');

Info: You should always use the array format if your SELECT clause contains SQL expressions. This is because a SQL expression like CONCAT(first_name, last_name) AS full_name may contain commas. If you list it together with other columns in a string, the expression may be split into several parts by commas, which is not what you want to see.

When specifying columns, you may include the table prefixes or column aliases, e.g., user.iduser.id AS user_id. If you are using array to specify the columns, you may also use the array keys to specify the column aliases, e.g.,['user_id' => 'user.id', 'user_name' => 'user.name'].

Starting from version 2.0.1, you may also select sub-queries as columns. For example,

$subQuery = (new Query)->select('COUNT(*)')->from('user'); $query = (new Query)->select(['id', 'count' => $subQuery])->from('post'); // $query represents the following SQL: // SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`

To select distinct rows, you may call distinct(), like the following:

$query->select('user_id')->distinct()->from('post');

FROM

To specify which table(s) to select data from, call from():

$query->select('*')->from('user');

You may specify multiple tables using a comma-separated string or an array. Table names can contain schema prefixes (e.g. 'public.user') and/or table aliases (e.g. 'user u'). The method will automatically quote the table names unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). For example,

$query->select('u.*, p.*')->from(['user u', 'post p']);

When the tables are specified as an array, you may also use the array keys as the table aliases (if a table does not need alias, do not use a string key). For example,

$query->select('u.*, p.*')->from(['u' => 'user', 'p' => 'post']);

You may specify a sub-query using a Query object. In this case, the corresponding array key will be used as the alias for the sub-query.

$subQuery = (new Query())->select('id')->from('user')->where('status=1'); $query->select('*')->from(['u' => $subQuery]);

WHERE

Usually data is selected based upon certain criteria. Query Builder has some useful methods to specify these, the most powerful of which being where. It can be used in multiple ways.

The simplest way to apply a condition is to use a string:

$query->where('status=:status', [':status' => $status]);

When using strings, make sure you're binding the query parameters, not creating a query by string concatenation. The above approach is safe to use, the following is not:

$query->where("status=$status"); // Dangerous!

Instead of binding the status value immediately, you can do so using params or addParams:

$query->where('status=:status'); $query->addParams([':status' => $status]);

Multiple conditions can simultaneously be set in where using the hash format:

$query->where([     'status' => 10,     'type' => 2,     'id' => [4, 8, 15, 16, 23, 42], ]);

That code will generate the following SQL:

WHERE (`status` = 10) AND (`type` = 2) AND (`id` IN (4, 8, 15, 16, 23, 42))

NULL is a special value in databases, and is handled smartly by the Query Builder. This code:

$query->where(['status' => null]);

results in this WHERE clause:

WHERE (`status` IS NULL)

You can also create sub-queries with Query objects like the following,

$userQuery = (new Query)->select('id')->from('user'); $query->where(['id' => $userQuery]);

which will generate the following SQL:

WHERE `id` IN (SELECT `id` FROM `user`)

Another way to use the method is the operand format which is [operator, operand1, operand2, ...].

Operator can be one of the following (see also [[yii\db\QueryInterface::where()]]):

  • and: the operands should be concatenated together using AND. For example, ['and', 'id=1', 'id=2'] will generate id=1 AND id=2. If an operand is an array, it will be converted into a string using the rules described here. For example, ['and', 'type=1', ['or', 'id=1', 'id=2']] will generate type=1 AND (id=1 OR id=2). The method will NOT do any quoting or escaping.

  • or: similar to the and operator except that the operands are concatenated using OR.

  • between: operand 1 should be the column name, and operand 2 and 3 should be the starting and ending values of the range that the column is in. For example, ['between', 'id', 1, 10] will generate id BETWEEN 1 AND 10.

  • not between: similar to between except the BETWEEN is replaced with NOT BETWEEN in the generated condition.

  • in: operand 1 should be a column or DB expression. Operand 2 can be either an array or a Query object. It will generate an IN condition. If Operand 2 is an array, it will represent the range of the values that the column or DB expression should be; If Operand 2 is a Query object, a sub-query will be generated and used as the range of the column or DB expression. For example, ['in', 'id', [1, 2, 3]] will generate id IN (1, 2, 3). The method will properly quote the column name and escape values in the range. The in operator also supports composite columns. In this case, operand 1 should be an array of the columns, while operand 2 should be an array of arrays or a Query object representing the range of the columns.

  • not in: similar to the in operator except that IN is replaced with NOT IN in the generated condition.

  • like: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing the values that the column or DB expression should be like. For example, ['like', 'name', 'tester'] will generatename LIKE '%tester%'. When the value range is given as an array, multiple LIKE predicates will be generated and concatenated using AND. For example, ['like', 'name', ['test', 'sample']] will generate name LIKE '%test%' AND name LIKE '%sample%'. You may also provide an optional third operand to specify how to escape special characters in the values. The operand should be an array of mappings from the special characters to their escaped counterparts. If this operand is not provided, a default escape mapping will be used. You may use falseor an empty array to indicate the values are already escaped and no escape should be applied. Note that when using an escape mapping (or the third operand is not provided), the values will be automatically enclosed within a pair of percentage characters.

    Note: When using PostgreSQL you may also use ilike instead of like for case-insensitive matching.

  • or like: similar to the like operator except that OR is used to concatenate the LIKE predicates when operand 2 is an array.

  • not like: similar to the like operator except that LIKE is replaced with NOT LIKE in the generated condition.

  • or not like: similar to the not like operator except that OR is used to concatenate the NOT LIKE predicates.

  • exists: requires one operand which must be an instance of [[yii\db\Query]] representing the sub-query. It will build a EXISTS (sub-query) expression.

  • not exists: similar to the exists operator and builds a NOT EXISTS (sub-query) expression.

Additionally you can specify anything as operator:

$query->select('id')     ->from('user')     ->where(['>=', 'id', 10]);

It will result in:

SELECT id FROM user WHERE id >= 10;

If you are building parts of condition dynamically it's very convenient to use andWhere() and orWhere():

$status = 10; $search = 'yii';  $query->where(['status' => $status]); if (!empty($search)) {     $query->andWhere(['like', 'title', $search]); }

In case $search isn't empty the following SQL will be generated:

WHERE (`status` = 10) AND (`title` LIKE '%yii%')

Building Filter Conditions

When building filter conditions based on user inputs, you usually want to specially handle "empty inputs" by ignoring them in the filters. For example, you have an HTML form that takes username and email inputs. If the user only enters something in the username input, you may want to build a query that only tries to match the entered username. You may use the filterWhere() method to achieve this goal:

// $username and $email are from user inputs $query->filterWhere([     'username' => $username,     'email' => $email, ]);

The filterWhere() method is very similar to where(). The main difference is that filterWhere() will remove empty values from the provided condition. So if $email is "empty", the resulting query will be ...WHERE username=:username; and if both $username and $email are "empty", the query will have no WHERE part.

A value is empty if it is null, an empty string, a string consisting of whitespaces, or an empty array.

You may also use andFilterWhere() and orFilterWhere() to append more filter conditions.

ORDER BY

For ordering results orderBy and addOrderBy could be used:

$query->orderBy([     'id' => SORT_ASC,     'name' => SORT_DESC, ]);

Here we are ordering by id ascending and then by name descending.

GROUP BY and HAVING

In order to add GROUP BY to generated SQL you can use the following:

$query->groupBy('id, status');

If you want to add another field after using groupBy:

$query->addGroupBy(['created_at', 'updated_at']);

To add a HAVING condition the corresponding having method and its andHaving and orHaving can be used. Parameters for these are similar to the ones for where methods group:

$query->having(['status' => $status]);

LIMIT and OFFSET

To limit result to 10 rows limit can be used:

$query->limit(10);

To skip 100 fist rows use:

$query->offset(100);

JOIN

The JOIN clauses are generated in the Query Builder by using the applicable join method:

  • innerJoin()
  • leftJoin()
  • rightJoin()

This left join selects data from two related tables in one query:

$query->select(['user.name AS author', 'post.title as title'])     ->from('user')     ->leftJoin('post', 'post.user_id = user.id');

In the code, the leftJoin() method's first parameter specifies the table to join to. The second parameter defines the join condition.

If your database application supports other join types, you can use those via the generic join method:

$query->join('FULL OUTER JOIN', 'post', 'post.user_id = user.id');

The first argument is the join type to perform. The second is the table to join to, and the third is the condition.

Like FROM, you may also join with sub-queries. To do so, specify the sub-query as an array which must contain one element. The array value must be a Query object representing the sub-query, while the array key is the alias for the sub-query. For example,

$query->leftJoin(['u' => $subQuery], 'u.id=author_id');

UNION

UNION in SQL adds results of one query to results of another query. Columns returned by both queries should match. In Yii in order to build it you can first form two query objects and then use union method:

$query = new Query(); $query->select("id, category_id as type, name")->from('post')->limit(10);  $anotherQuery = new Query(); $anotherQuery->select('id, type, name')->from('user')->limit(10);  $query->union($anotherQuery);

Batch Query

When working with large amount of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, Yii provides the so-called batch query support. A batch query makes uses of data cursor and fetches data in batches.

Batch query can be used like the following:

use yii\db\Query;  $query = (new Query())     ->from('user')     ->orderBy('id');  foreach ($query->batch() as $users) {     // $users is an array of 100 or fewer rows from the user table }  // or if you want to iterate the row one by one foreach ($query->each() as $user) {     // $user represents one row of data from the user table }

The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the Iterator interface and thus can be used in the foreach construct. During the first iteration, a SQL query is made to the database. Data are since then fetched in batches in the iterations. By default, the batch size is 100, meaning 100 rows of data are being fetched in each batch. You can change the batch size by passing the first parameter to the batch() or each() method.

Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory. If you process the data and then discard it right away, the batch query can help keep the memory usage under a limit.

If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query will still keep the proper index. For example,

use yii\db\Query;  $query = (new Query())     ->from('user')     ->indexBy('username');  foreach ($query->batch() as $users) {     // $users is indexed by the "username" column }  foreach ($query->each() as $username => $user) { }
 

Tags: yii, yii2

Yii2-smarty的一些小坑

在写本文前我不得不说一句,其实我是不想用smarty的,我想尝试一下twig,但是phpstorm的Twig插件真要命,卡成翔,所以我只能用smarty。为什么不用prado了呢?官方说不支持了,我晶啊

在使用smarty的时候官方的代码和例子看上去很美,不过要注意几点

1、用yii2-smarty,还是必须得用layout,如果你不支持layout文件,默认就是/layouts/main.php,天啊,为什么是PHP?而且在这里面也还真的能用PHP代码。整个都崩溃了

2、你可以指定layout文件,比如:main.tpl,OK你必须得象PHP文件一样,得写{$this->head()},{$this->startBody()}{$this->endPage()}等,否则 ClientScript功能就无法使用

3、如果你指定layout=false,那么,就不支持ClientScript了。因为你incude file='xxx.tpl',在每一个独立的文件里都必须要象2中一个个的this->head(),this->endPage全写上

4、再来一个bug:{registerJsFile url=''},这个函数有BUG

原来是:

PHP代码
  1. public function functionRegisterJsFile($params$template)  
  2. {  
  3.     if (!isset($params['url'])) {  
  4.         trigger_error("registerJsFile: missing 'url' parameter");  
  5.     }  
  6.   
  7.     $url = ArrayHelper::remove($params'url');  
  8.     $key = ArrayHelper::remove($params'key', null);  
  9.     $depends = ArrayHelper::remove($params'depends', null);  
  10.     if (isset($params['position']))  
  11.         $params['position'] = $this->getViewConstVal($params['position'], View::POS_END);  
  12.   
  13.     Yii::$app->getView()->registerJsFile($url$depends$params$key);  
  14. }  

改成为:

PHP代码
  1. /** 
  2.  * Smarty function plugin 
  3.  * Usage is the following: 
  4.  * 
  5.  * {registerJsFile url='http://maps.google.com/maps/api/js?sensor=false' position='POS_END'} 
  6.  * 
  7.  * Supported attributes: url, key, depends, position and valid HTML attributes for the script tag. 
  8.  * Refer to Yii documentation for details. 
  9.  * The position attribute is passed as text without the class prefix. 
  10.  * Default is 'POS_END'. 
  11.  * 
  12.  * @param $params 
  13.  * @param \Smarty_Internal_Template $template 
  14.  * @return string 
  15.  * @note Even though this method is public it should not be called directly. 
  16.  */  
  17. public function functionRegisterJsFile($params$template)  
  18. {  
  19.     if (!isset($params['url'])) {  
  20.         trigger_error("registerJsFile: missing 'url' parameter");  
  21.     }  
  22.   
  23.     $url = ArrayHelper::remove($params'url');  
  24.     $key = ArrayHelper::remove($params'key', null);  
  25.     $params['depends'] = ArrayHelper::remove($params'depends', null);  
  26.     if (isset($params['position']))  
  27.         $params['position'] = $this->getViewConstVal($params['position'], View::POS_END);  
  28.   
  29.     Yii::$app->getView()->registerJsFile($url$params$key);  
  30. }  

其实就是$params['depends']这个参数。registerJsFile只能接受3个参数,但事实上用了4个参数,所以调整一下即可

 

Tags: yii2, smarty, twig