Yii includes a built-in error handler which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:
- All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
- Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
in debug mode. - Supports using a dedicated controller action to display errors.
- Supports different error response formats.
The error handler is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.
Using Error Handler ¶
The error handler is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:
return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 20,
],
],
];
With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.
As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:
use Yii;
use yiibaseErrorException;
try {
10/0;
} catch (ErrorException $e) {
Yii::warning("Division by zero.");
}
// execution continues...
If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an HTTP exception, such as yiiwebNotFoundHttpException. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.
use yiiwebNotFoundHttpException;
throw new NotFoundHttpException();
Customizing Error Display ¶
The error handler adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.
Info: If an exception is a descendant of yiibaseUserException, no call stack will be displayed regardless
the value ofYII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.
By default, the error handler displays errors using two views:
@yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
WhenYII_DEBUGisfalse, this is the only error view to be displayed.@yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.
You can configure the errorView and exceptionView
properties of the error handler to use your own views to customize the error display.
Using Error Actions ¶
A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the errorAction property of the errorHandler
component like the following:
return [
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
]
];
The errorAction property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.
You can create the site/error action as follows,
namespace appcontrollers;
use Yii;
use yiiwebController;
class SiteController extends Controller
{
public function actions()
{
return [
'error' => [
'class' => 'yiiwebErrorAction',
],
];
}
}
The above code defines the error action using the yiiwebErrorAction class which renders an error
using a view named error.
Besides using yiiwebErrorAction, you may also define the error action using an action method like the following,
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}
You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as yiiwebErrorAction:
name: the name of the error;message: the error message;exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
error code, error call stack, etc.
Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.
Note: If you need to redirect in an error handler, do it the following way:
Yii::$app->getResponse()->redirect($url)->send(); return;
Customizing Error Response Format ¶
The error handler displays errors according to the format setting of the response.
If the response format is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the yiiwebResponse::$data property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:
HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:
return [
// ...
'components' => [
'response' => [
'class' => 'yiiwebResponse',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
],
],
];
The above code will reformat the error response like the following:
HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"success": false,
"data": {
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
}
I want to display 404 error page for that i have made error404.php file in my protected/view/system folder.
By default i have Sitecontroller and it contained error action function as below
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
inside main config file it is defined as
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
my problem is i need to customize 404 page only, rest of the error i need to handle the way it is being handle by sitecontroller’s error function. But i could not find a way to do that. If suppose i remove ‘errorAction’=>’site/error’, from the config main then it does show the 404 error by calling
throw new CHttpException(404, 'Page not found');
but doing that i can only see the page without layout also other custom errors are treated same as 404 while they are not. I read the manual many times but i still cant able to resolve it.
Yii includes a built-in [[yiiwebErrorHandler|error handler]] which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:
- All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
- Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
in debug mode. - Supports using a dedicated controller action to display errors.
- Supports different error response formats.
The [[yiiwebErrorHandler|error handler]] is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.
Using Error Handler
The [[yiiwebErrorHandler|error handler]] is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:
return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 20,
],
],
];
With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.
As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:
use Yii;
use yiibaseErrorException;
try {
10/0;
} catch (ErrorException $e) {
Yii::warning("Division by zero.");
}
// execution continues...
If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an [[yiiwebHttpException|HTTP exception]], such as [[yiiwebNotFoundHttpException]]. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.
use yiiwebNotFoundHttpException;
throw new NotFoundHttpException();
Customizing Error Display
The [[yiiwebErrorHandler|error handler]] adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.
Info: If an exception is a descendant of [[yiibaseUserException]], no call stack will be displayed regardless
the value ofYII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.
By default, the [[yiiwebErrorHandler|error handler]] displays errors using two views:
@yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
WhenYII_DEBUGis false, this is the only error view to be displayed.@yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.
You can configure the [[yiiwebErrorHandler::errorView|errorView]] and [[yiiwebErrorHandler::exceptionView|exceptionView]]
properties of the error handler to use your own views to customize the error display.
Using Error Actions
A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the [[yiiwebErrorHandler::errorAction|errorAction]] property of the errorHandler
component like the following:
return [
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
]
];
The [[yiiwebErrorHandler::errorAction|errorAction]] property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.
You can create the site/error action as follows,
namespace appcontrollers;
use Yii;
use yiiwebController;
class SiteController extends Controller
{
public function actions()
{
return [
'error' => [
'class' => 'yiiwebErrorAction',
],
];
}
}
The above code defines the error action using the [[yiiwebErrorAction]] class which renders an error
using a view named error.
Besides using [[yiiwebErrorAction]], you may also define the error action using an action method like the following,
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}
You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as [[yiiwebErrorAction]]:
name: the name of the error;message: the error message;exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
error code, error call stack, etc.
Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.
Customizing Error Response Format
The error handler displays errors according to the format setting of the response.
If the the [[yiiwebResponse::format|response format]] is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the [[yiiwebResponse::data]] property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:
HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:
return [
// ...
'components' => [
'response' => [
'class' => 'yiiwebResponse',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
],
],
];
The above code will reformat the error response like the following:
HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"success": false,
"data": {
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
}
Handling Errors
Yii includes a built-in [[yiiwebErrorHandler|error handler]] which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:
- All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
- Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
in debug mode. - Supports using a dedicated controller action to display errors.
- Supports different error response formats.
The [[yiiwebErrorHandler|error handler]] is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.
Using Error Handler
The [[yiiwebErrorHandler|error handler]] is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:
return [ 'components' => [ 'errorHandler' => [ 'maxSourceLines' => 20, ], ], ];
With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.
As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:
use Yii; use yiibaseErrorException; try { 10/0; } catch (ErrorException $e) { Yii::warning("Division by zero."); } // execution continues...
If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an [[yiiwebHttpException|HTTP exception]], such as [[yiiwebNotFoundHttpException]]. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.
use yiiwebNotFoundHttpException; throw new NotFoundHttpException();
Customizing Error Display
The [[yiiwebErrorHandler|error handler]] adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.
Info: If an exception is a descendant of [[yiibaseUserException]], no call stack will be displayed regardless
the value ofYII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.
By default, the [[yiiwebErrorHandler|error handler]] displays errors using two views:
@yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
WhenYII_DEBUGisfalse, this is the only error view to be displayed.@yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.
You can configure the [[yiiwebErrorHandler::errorView|errorView]] and [[yiiwebErrorHandler::exceptionView|exceptionView]]
properties of the error handler to use your own views to customize the error display.
Using Error Actions
A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the [[yiiwebErrorHandler::errorAction|errorAction]] property of the errorHandler
component like the following:
return [ 'components' => [ 'errorHandler' => [ 'errorAction' => 'site/error', ], ] ];
The [[yiiwebErrorHandler::errorAction|errorAction]] property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.
You can create the site/error action as follows,
namespace appcontrollers; use Yii; use yiiwebController; class SiteController extends Controller { public function actions() { return [ 'error' => [ 'class' => 'yiiwebErrorAction', ], ]; } }
The above code defines the error action using the [[yiiwebErrorAction]] class which renders an error
using a view named error.
Besides using [[yiiwebErrorAction]], you may also define the error action using an action method like the following,
public function actionError() { $exception = Yii::$app->errorHandler->exception; if ($exception !== null) { return $this->render('error', ['exception' => $exception]); } }
You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as [[yiiwebErrorAction]]:
name: the name of the error;message: the error message;exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
error code, error call stack, etc.
Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.
Note: If you need to redirect in an error handler, do it the following way:
Yii::$app->getResponse()->redirect($url)->send(); return;
Customizing Error Response Format
The error handler displays errors according to the format setting of the response.
If the [[yiiwebResponse::format|response format]] is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the [[yiiwebResponse::data]] property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:
HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:
return [ // ... 'components' => [ 'response' => [ 'class' => 'yiiwebResponse', 'on beforeSend' => function ($event) { $response = $event->sender; if ($response->data !== null) { $response->data = [ 'success' => $response->isSuccessful, 'data' => $response->data, ]; $response->statusCode = 200; } }, ], ], ];
The above code will reformat the error response like the following:
HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
{
"success": false,
"data": {
"name": "Not Found Exception",
"message": "The requested resource was not found.",
"code": 0,
"status": 404
}
}
После установки Yii2 уже имеется файл view-шаблона views/site/error.php. Чтобы получить свою страницу ошибки, можно просто отредактировать этот файл. В нём доступны три переменные: $name, $message, $exception. Признак ошибки 404 — это значение свойства statusCode объекта $exception. Таким образом можно написать свою проверку этого значения и для разных ошибок показывать пользователю разный ответ.
Почему для показа сообщения об ошибках используется шаблон views/site/error.php? Это задается в настройках приложения, в файле config/web.php:
$config = [ /* ... */ 'components' => [ /* ... */ 'errorHandler' => [ 'errorAction' => 'site/error' ], /* ... */ ], /* ... */ ];
Для обработки ошибок будет использован метод actionError() класса SiteController:
class SiteController extends Controller { /* ... */ public function actionError() { $exception = Yii::$app->errorHandler->exception; if ($exception !== null) { return $this->render('error', ['exception' => $exception]); } } /* ... */ }
Но если мы заглянем в исходный код controllers/SiteController.php, то обнаружим, что такого метода там нет. А вместо него есть метод actions():
class SiteController extends Controller { /* ... */ public function actions() { return [ 'error' => [ // объявляем действие error и задаем имя класса 'class' => 'yiiwebErrorAction', ], ]; } /* ... */ }
Все действия контроллера можно разделить на встроенные и отдельные. Встроенные действия определены как методы контроллера, например actionError(). Отдельные действия указываются в карте действий контроллера, в методе actions(). Сам же функционал таких действий описан в отдельных классах.
Мы договорились ранее использовать класс SiteController только как образец. Давайте зададим свой обработчик ошибки в файле конфигурации config/web.php:
$config = [ /* ... */ 'components' => [ /* ... */ 'errorHandler' => [ 'errorAction' => 'app/error' ], /* ... */ ], /* ... */ ];
Добавим метод actions() в класс AppController:
class AppController extends Controller { /* ... */ public function actions() { return [ 'error' => [ 'class' => 'yiiwebErrorAction', ], ]; } /* ... */ }
Создадим view-шаблон views/app/error.php:
<?php /* @var $this yiiwebView */ /* @var $name string */ /* @var $message string */ /* @var $exception Exception */ use yiihelpersHtml; $this->title = $name; ?> <div class="container"> <h1><?= Html::encode($this->title) ?></h1> <div class="alert alert-danger"> <?= nl2br(Html::encode($message)) ?> </div> </div>
И внесем изменения в класс CatalogController, чтобы он выбрасывал исключение, когда в базе данных не удается найти категорию, бренд или товар каталога:
<?php namespace appcontrollers; use appmodelsCategory; use appmodelsBrand; use appmodelsProduct; use yiiwebHttpException; use Yii; class CatalogController extends AppController { /** * Главная страница каталога товаров */ public function actionIndex() { // получаем корневые категории $roots = Yii::$app->cache->get('root-categories'); if ($roots === false) { $roots = Category::find()->where(['parent_id' => 0])->asArray()->all(); Yii::$app->cache->set('root-categories', $roots); } // получаем популярные бренды $brands = Yii::$app->cache->get('popular-brands'); if ($brands === false) { $brands = (new Brand())->getPopularBrands(); Yii::$app->cache->set('popular-brands', $brands); } return $this->render('index', compact('roots', 'brands')); } /** * Категория каталога товаров */ public function actionCategory($id, $page = 1) { $id = (int)$id; $page = (int)$page; // пробуем извлечь данные из кеша $data = Yii::$app->cache->get('category-'.$id.'-page-'.$page); if ($data === null) { // данные есть в кеше, но такой категории не существует throw new HttpException( 404, 'Запрошенная страница не найдена' ); } if ($data === false) { // данных нет в кеше, получаем их заново $temp = new Category(); // данные о категории $category = $temp->getCategory($id); if (!empty($category)) { // такая категория существует // товары категории list($products, $pages) = $temp->getCategoryProducts($id); // сохраняем полученные данные в кеше $data = [$products, $pages, $category]; Yii::$app->cache->set('category-' . $id . '-page-' . $page, $data); } else { // такая категория не существует Yii::$app->cache->set('category-' . $id . '-page-' . $page, null); throw new HttpException( 404, 'Запрошенная страница не найдена' ); } } list($products, $pages, $category) = $data; // устанавливаем мета-теги для страницы $this->setMetaTags( $category['name'] . ' | ' . Yii::$app->params['shopName'], $category['keywords'], $category['description'] ); return $this->render( 'category', compact('category', 'products', 'pages') ); } /** * Список всех брендов каталога товаров */ public function actionBrands() { // пробуем извлечь данные из кеша $brands = Yii::$app->cache->get('all-brands'); if ($brands === false) { // данных нет в кеше, получаем их заново $brands = (new Brand())->getAllBrands(); // сохраняем полученные данные в кеше Yii::$app->cache->set('all-brands', $brands); } return $this->render( 'brands', compact('brands') ); } /** * Список товаров бренда с идентификатором $id */ public function actionBrand($id, $page = 1) { $id = (int)$id; $page = (int)$page; // пробуем извлечь данные из кеша $data = Yii::$app->cache->get('brand-'.$id.'-page-'.$page); if ($data === null) { // данные есть в кеше, но такого бренда не существует throw new HttpException( 404, 'Запрошенная страница не найдена' ); } if ($data === false) { // данных нет в кеше, получаем их заново $temp = new Brand(); // данные о бренде $brand = $temp->getBrand($id); if (!empty($brand)) { // такой бренд существует // товары бренда list($products, $pages) = $temp->getBrandProducts($id); // сохраняем полученные данные в кеше $data = [$products, $pages, $brand]; Yii::$app->cache->set('brand-'.$id.'-page-'.$page, $data); } else { // такой бренд не существует Yii::$app->cache->set('brand-'.$id.'-page-'.$page, null); throw new HttpException( 404, 'Запрошенная страница не найдена' ); } } list($products, $pages, $brand) = $data; // устанавливаем мета-теги $this->setMetaTags( $brand['name'] . ' | ' . Yii::$app->params['shopName'], $brand['keywords'], $brand['description'] ); return $this->render( 'brand', compact('brand', 'products', 'pages') ); } /** * Страница товара с идентификатором $id */ public function actionProduct($id) { $id = (int)$id; // пробуем извлечь данные из кеша $data = Yii::$app->cache->get('product-'.$id); if ($data === null) { // данные есть в кеше, но такого товара не существует throw new HttpException( 404, 'Запрошенная страница не найдена' ); } if ($data === false) { // данных нет в кеше, получаем их заново $product = (new Product())->getProduct($id); if (!empty($product)) { // такой товар существует $brand = (new Brand())->getBrand($product['brand_id']); $data = [$product, $brand]; // сохраняем полученные данные в кеше Yii::$app->cache->set('product-' . $id, $data); } else { // такого товара не существует Yii::$app->cache->set('product-' . $id, null); throw new HttpException( 404, 'Запрошенная страница не найдена' ); } } list($product, $brand) = $data; // устанавливаем мета-теги $this->setMetaTags( $product['name'] . ' | ' . Yii::$app->params['shopName'], $product['keywords'], $product['description'] ); // получаем популярные товары, похожие на текущий $similar = Yii::$app->cache->get('similar-'.$product['id']); if ($similar === false) { // товары из той же категории того же бренда $similar = Product::find() ->where([ 'hit' => 1, 'category_id' => $product['category_id'], 'brand_id' => $product['brand_id'] ]) ->andWhere(['NOT IN', 'id', $product['id']]) ->limit(3) ->asArray() ->all(); Yii::$app->cache->set('similar-'.$product['id'], $similar); } return $this->render( 'product', compact('product', 'brand', 'similar') ); } }
Поиск:
Web-разработка • Yii2 • Интернет магазин • Исключение • Каталог товаров • Практика • Фреймворк • 404 • Not Found • Exception • Ошибка • Error
Каталог оборудования
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Производители
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Функциональные группы
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
