Skip to content

Commit

Permalink
Merge pull request yiisoft#1 from yiisoft/master
Browse files Browse the repository at this point in the history
Merge from yiisoft
  • Loading branch information
sensorario committed May 5, 2013
2 parents ac8c6c1 + 34789ff commit 1451aa6
Show file tree
Hide file tree
Showing 43 changed files with 315 additions and 47 deletions.
14 changes: 14 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: php

php:
- 5.3
- 5.4
- 5.5

env:
- DB=mysql

before_script:
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS yiitest;'; fi"

script: phpunit
2 changes: 1 addition & 1 deletion build/build
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ require(__DIR__ . '/../framework/yii.php');
$id = 'yiic-build';
$basePath = __DIR__;

$application = new yii\console\Application($id, $basePath);
$application = new yii\console\Application(array('id' => $id, 'basePath' => $basePath));
$application->run();
Empty file added docs/guide/active-record.md
Empty file.
Empty file added docs/guide/authentication.md
Empty file.
Empty file added docs/guide/authorization.md
Empty file.
3 changes: 3 additions & 0 deletions docs/guide/caching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Caching
=======

Empty file added docs/guide/console.md
Empty file.
Empty file added docs/guide/dao.md
Empty file.
3 changes: 3 additions & 0 deletions docs/guide/error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Error Handling
==============

Empty file added docs/guide/extension.md
Empty file.
Empty file added docs/guide/form.md
Empty file.
Empty file added docs/guide/gii.md
Empty file.
Empty file added docs/guide/i18n.md
Empty file.
11 changes: 6 additions & 5 deletions docs/guide/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@ http://hostname/path/to/yii/requirements/index.php
~~~

Yii requires PHP 5.3, so the server must have PHP 5.3 or above installed and
available to the web server. Yii has been tested with [Apache HTTP server](http://httpd.apache.org/)
on Windows and Linux. It may also run on other Web servers and platforms,
available to the web server. Yii has been tested with [Apache HTTP server](http://httpd.apache.org/)
on Windows and Linux. It may also run on other Web servers and platforms,
provided PHP 5.3 is supported.


Recommended Apache Configuration
--------------------------------

Yii is ready to work with a default Apache web server configuration.
The `.htaccess` files in Yii framework and application folders restrict
The `.htaccess` files in Yii framework and application folders deny
access to the restricted resources. To hide the bootstrap file (usually `index.php`)
in your URLs you can add `mod_rewrite` instructions to the `.htaccess` file
in your document root or to the virtual host configuration:
Expand Down Expand Up @@ -63,7 +63,7 @@ server {
access_log /www/mysite/log/access.log main;
server_name mysite;
root $host_path/htdocs;
root $host_path/htdocs;
set $yii_bootstrap "index.php";
charset utf-8;
Expand Down Expand Up @@ -108,4 +108,5 @@ server {
}
~~~

Using this configuration you can set `cgi.fix_pathinfo=0` in php.ini to avoid many unnecessary system stat() calls.
Using this configuration you can set `cgi.fix_pathinfo=0` in php.ini to avoid
many unnecessary system `stat()` calls.
Empty file added docs/guide/logging.md
Empty file.
3 changes: 3 additions & 0 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Database Migration
==================

3 changes: 2 additions & 1 deletion docs/guide/mvc.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ the communication between the model and the view.

Besides implementing MVC, Yii also introduces a front-controller, called
`Application`, which encapsulates the execution context for the processing
of a request. Application collects some information about a user request and
of a request. Application collects information about a user request and
then dispatches it to an appropriate controller for further handling.

The following diagram shows the static structure of a Yii application:
Expand All @@ -21,6 +21,7 @@ The following diagram shows the static structure of a Yii application:

A Typical Workflow
------------------

The following diagram shows a typical workflow of a Yii application when
it is handling a user request:

Expand Down
181 changes: 181 additions & 0 deletions docs/guide/performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
Performance Tuning
==================

Application performance consists of two parts. First is the framework performance
and the second is the application itself. Yii has a pretty low performance impact
on your application out of the box and can be fine-tuned further for production
environment. As for the application, we'll provide some of the best practices
along with examples on how to apply them to Yii.

Preparing framework for production
----------------------------------

### Disabling Debug Mode

First thing you should do before deploying your application to production environment
is to disable debug mode. A Yii application runs in debug mode if the constant
`YII_DEBUG` is defined as `true` in `index.php` so to disable debug the following
should be in your `index.php`:

```php
defined('YII_DEBUG') or define('YII_DEBUG', false);
```

Debug mode is very useful during development stage, but it would impact performance
because some components cause extra burden in debug mode. For example, the message
logger may record additional debug information for every message being logged.

### Enabling PHP opcode cache

Enabling the PHP opcode cache improves any PHP application performance and lowers
memory usage significantly. Yii is no exception. It was tested with
[APC PHP extension](http://php.net/manual/en/book.apc.php) that caches
and optimizes PHP intermediate code and avoids the time spent in parsing PHP
scripts for every incoming request.

### Turning on ActiveRecord database schema caching

If the application is using Active Record, we should turn on the schema caching
to save the time of parsing database schema. This can be done by setting the
`Connection::enableSchemaCache` property to be `true` via application configuration
`protected/config/main.php`:

```php
return array(
// ...
'components' => array(
// ...
'db' => array(
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root',
'password' => '',
'enableSchemaCache' => true,

// Duration of schema cache.
// 'schemaCacheDuration' => 3600,

// Name of the cache component used. Default is 'cache'.
//'schemaCache' => 'cache',
),
'cache' => array(
'class' => 'yii\caching\FileCache',
),
),
);
```

Note that `cache` application component should be configured.

### Combining and Minimizing Assets

TBD

### Using better storage for sessions

By default PHP uses files to handle sessions. It is OK for development and
small projects but when it comes to handling concurrent requests it's better to
switch to another storage such as database. You can do so by configuring your
application via `protected/config/main.php`:

```php
return array(
// ...
'components' => array(
'session' => array(
'class' => 'yii\web\DbSession',

// Set the following if want to use DB component other than
// default 'db'.
// 'db' => 'mydb',

// To override default session table set the following
// 'sessionTable' => 'my_session',
),
),
);
```

You can use `CacheSession` to store sessions using cache. Note that some
cache storages such as memcached has no guaranteee that session data will not
be lost leading to unexpected logouts.

Improving application
---------------------

### Using Serverside Caching Techniques

As described in the Caching section, Yii provides several caching solutions that
may improve the performance of a Web application significantly. If the generation
of some data takes long time, we can use the data caching approach to reduce the
data generation frequency; If a portion of page remains relatively static, we
can use the fragment caching approach to reduce its rendering frequency;
If a whole page remains relative static, we can use the page caching approach to
save the rendering cost for the whole page.


### Leveraging HTTP to save procesing time and bandwidth

TBD

### Database Optimization

Fetching data from database is often the main performance bottleneck in
a Web application. Although using caching may alleviate the performance hit,
it does not fully solve the problem. When the database contains enormous data
and the cached data is invalid, fetching the latest data could be prohibitively
expensive without proper database and query design.

Design index wisely in a database. Indexing can make SELECT queries much faster,
but it may slow down INSERT, UPDATE or DELETE queries.

For complex queries, it is recommended to create a database view for it instead
of issuing the queries inside the PHP code and asking DBMS to parse them repetitively.

Do not overuse Active Record. Although Active Record is good at modelling data
in an OOP fashion, it actually degrades performance due to the fact that it needs
to create one or several objects to represent each row of query result. For data
intensive applications, using DAO or database APIs at lower level could be
a better choice.

Last but not least, use LIMIT in your SELECT queries. This avoids fetching
overwhelming data from database and exhausting the memory allocated to PHP.

### Using asArray

A good way to save memory and processing time on read-only pages is to use
ActiveRecord's `asArray` method.

```php
class PostController extends Controller
{
public function actionIndex()
{
$posts = Post::find()->orderBy('id DESC')->limit(100)->asArray()->all();
echo $this->render('index', array(
'posts' => $posts,
));
}
}
```

In the view you should access fields of each invidual record from `$posts` as array:

```php
foreach($posts as $post) {
echo $post['title']."<br>";
}
```

Note that you can use array notation even if `asArray` wasn't specified and you're
working with AR objects.

### Processing data in background

In order to respond to user requests faster you can process heavy parts of the
request later if there's no need for immediate response.

- Cron jobs + console.
- queues + handlers.

TBD
Empty file added docs/guide/query-builder.md
Empty file.
Empty file added docs/guide/security.md
Empty file.
3 changes: 3 additions & 0 deletions docs/guide/template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Template
========

Empty file added docs/guide/testing.md
Empty file.
Empty file added docs/guide/theming.md
Empty file.
Empty file added docs/guide/upgrade.md
Empty file.
3 changes: 3 additions & 0 deletions docs/guide/url.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
URL Management
==============

Empty file added docs/guide/validation.md
Empty file.
3 changes: 3 additions & 0 deletions docs/view_renderers.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ array(
)
```

Note that Smarty and Twig are not bundled with Yii and you have to download and
unpack these yourself and then specify `twigPath` and `smartyPath` respectively.

Twig
----

Expand Down
9 changes: 8 additions & 1 deletion framework/YiiBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,13 @@ public static function powered()
*/
public static function t($message, $params = array(), $language = null)
{
return self::$app->getI18N()->translate($message, $params, $language);
if (self::$app !== null) {
return self::$app->getI18N()->translate($message, $params, $language);
} else {
if (strpos($message, '|') !== false && preg_match('/^([\w\-\\/\.\\\\]+)\|(.*)/', $message, $matches)) {
$message = $matches[2];
}
return is_array($params) ? strtr($message, $params) : $message;
}
}
}
3 changes: 2 additions & 1 deletion framework/base/Widget.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ public function run()
*/
public function render($view, $params = array())
{
return $this->view->render($view, $params, $this);
$viewFile = $this->findViewFile($view);
return $this->view->renderFile($viewFile, $params, $this);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion framework/db/ActiveRelation.php
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ private function filterByModels($models)
{
$attributes = array_keys($this->link);
$values = array();
if (count($attributes) ===1) {
if (count($attributes) === 1) {
// single key
$attribute = reset($this->link);
foreach ($models as $model) {
Expand Down
2 changes: 1 addition & 1 deletion framework/db/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ public function quoteColumnName($name)
public function quoteSql($sql)
{
$db = $this;
return preg_replace_callback('/(\\{\\{([\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
return preg_replace_callback('/(\\{\\{([%\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function($matches) use($db) {
if (isset($matches[3])) {
return $db->quoteColumnName($matches[3]);
Expand Down
4 changes: 2 additions & 2 deletions framework/db/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ public function orHaving($condition, $params = array())
* Sets the ORDER BY part of the query.
* @param string|array $columns the columns (and the directions) to be ordered by.
* Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array
* (e.g. `array('id' => Query::SORT_ASC ASC, 'name' => Query::SORT_DESC)`).
* (e.g. `array('id' => Query::SORT_ASC, 'name' => Query::SORT_DESC)`).
* The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression).
* @return Query the query object itself
Expand All @@ -499,7 +499,7 @@ public function orderBy($columns)
* Adds additional ORDER BY columns to the query.
* @param string|array $columns the columns (and the directions) to be ordered by.
* Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array
* (e.g. `array('id' => Query::SORT_ASC ASC, 'name' => Query::SORT_DESC)`).
* (e.g. `array('id' => Query::SORT_ASC, 'name' => Query::SORT_DESC)`).
* The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression).
* @return Query the query object itself
Expand Down
Loading

0 comments on commit 1451aa6

Please sign in to comment.