Yii2 удалить файл из папки
Давайте рассмотрим как в Yii2 прикреплять изображения к статье, обновлять их и удалять через AJAX. Я предполагаю что у вас уже сгенерированн CRUD для ваших задач.
Для начала создадим новую ячейку в БД в моём случае это бует таблица posts и ячейку я назову "logo". Тип Varchar длина 512, allow null.
Модель
В модели необходимо создать публичную переменную в которую мы будем передавать загружаемое изображение. Добвааляем её в класс модели models/Posts.php:
Далее в правилах валидации добавим правило для нашего файла: [['file'], 'file'], В моём случае набор правил будет выглядеть вот так:
Представление
Теперь давайте перейдём в наше представление views/posts/_form.php и в самом верху подключим хелперы:
Будьте внимательны, если вы создавали ваш CRUD не в ручную а например при помощи Gii то скорей всего хелпер yii\helpers\Html; у вас уже подключен и подключать его повторно не следует.
В параметрах формы необходимо указать что мы будем передавать файлы:
Теперь давайте создадим поле для загрузки изображения. Обратите внимание поле будет передавать данные в ранее созданую нами публичную переменную $file в модели Posts что бы затем контроллер мог сохранить отдельно файл в папку на сервере и записать имя файла в объект, а затем сохранить его в БД.
Далее прямо над полем для загрузки размещаем небольшой виджет который будет отображать загруженное изображение при просмотре статьи:
Давайте разберёмся что тут у нас происходит? Данный виджет будет виден только при редактировании уже ранее созданой статьи и только в том случае, если к статье уже было ранее добавленно изображение: if(!empty($model->logo)). Далее мы вызываем html хелпер Html::img который будет выдавать код типа и с качестве первого параметра принимает путь к файлу: Html::img($model->logo как раз наше изображение. Второй параметр у нас отвечает за размер изображения.
Контроллер
Для начала давайте подключим недостающий хелпер который занимается загрузкой файлов в Yii2:
Теперь необходимо в двух экшенах контроллера (созжание и обновление) необходимо добавить обработку передаваемого файла изображения. Для этого в экшенах public function actionCreate и public function actionUpdate сразу после строчки: if ($model->load(Yii::$app->request->post()) && $model->save()) добавляем вот такой код:
Давайте разберём его. В данном методе $imageName = time(); я получаю текущий тайм штам типа 1486298642 я буду использовать его как часть имени файла, что бы избежать конфликта одинаковых имён на сервере. Далее мы передаём в наш объект модели наш файл полученный из формы: $model->file = UploadedFile::getInstance($model, 'file'); через метод хелпер UploadedFile. Далее задаём условие, если файл загружен if(!empty($model->file)) сохраняем его в папку uploads в публичной директории сервера: $model->file->saveAs('uploads/blog_'.$imageName.'.'.$model->file->extension); затем к ранее созданному нами штампу добавляем префикс blog_ в результате загруженные файлы будут иметь имена вида blog_486298642 и затем добавляем точку и расширение оригинального файла '.'.$model->file->extension.
Теперь обратите внимание мы наконец отходим от работы с самим файлом который ранее хранился в переменной $file и передаём его имя и путь в объект модели в виде строки: $model->logo = 'uploads/blog_'.$imageName.'.'.$model->file->extension; Собственно осталось только сохранить данное состояние объекта $model->save(); что бы данные записались в БД. Это акупльно как в случае создания, так и обновления материала. Давайте ещё раз вернёмся на три строки выше к условию if(!empty($model->file)) мы его создали на тот случай, когда при обновлении материала мы не меняем текущее изображение или его вовсе нет. Без данного условия мы-бы получили ошибку о попытке передать пустой объект.
Удаление изображения через AJAX
Теперь давайте реализуем возможность удаления прикреплённого изображения без перезагрузки страницы, что весма полезно при обновлении материалов. Для начала, здесь же в контроллере создадим новый метод, который мы в дальнейшем и будем вызывать через AJAX запрос. Привожу полный код экшена:
Как видно из кода в качестве агрумента мы передаём ID объекта, далее создаём переменные с индификатором $model = $this->findModel($id); и путь до файла $imgName = $model->logo; Которые получаем из экземпляра объекта. Затем вызываем стандартный метод php - unlink() с параметром пути, который удаляет файл на сервере. Далее присваиваем экземпляру объекта значение null в для изображения и обновляем экземпляр модели $model->update(); в случае ели всё прошло успешно возвращяем строку Deleted которая будет отображена в форме.
Как видно из кода мы снова прибегли к помощи html хелпера для создания ссылки с AJAX запросом. Далее мы вызываем роутер которвый обращается к экшену удаления ['posts/deleteimage' и передаём переменную с id нашего объекта 'id' => $model->id]. Теперь после клика по ссылке отработает наш экшен на удаление и вернёт там ответ. В случае успеха сработает вот эта интересная часть AJAX:
Первая строка получит return из экшена где мы написали Deleted и отобразит его на экране, а вторая строка уберёт элемент картинки из DOM страницы.
Вот собственно и всё, теперь вы можете не засорять ваш сервер уже несуществующими изображениями.
P.S.
Это черновик статьи написвнный на скорую руку для закрепления только что проделанного опыта. Если у вас возникнут вопросы из за плохого изложения материала, или предложения по улучшению пожалуйста оставьте ваши комментарии.
Ищу разработчиков: NodeJS, PHP, удалённая работа. Зарплата в € Необходим опыт работы в FinTech. Практика работы со Stripe будет большим плюсом.
Расскажите кратко о себе и навыках в Telegram @markvi
Есть связанная таблица image из которой надо удалить строки в цикле вместе с картинками при удалении объявления, и в конце саму папку картинок
Путь картинок - пример: @web/upload/store/Adverts/Adverts8/b0cd8f.jpg
Помогите это все организовать, я примерно знаю как это будет работать. Но реализовать что то не получается
- Вопрос задан более трёх лет назад
- 534 просмотра
Добрый день.
Связь по внешнему ключу есть?
Если есть, то при удалении записи будут удаляться записи из таблицы image.
А директорию можно удалить так:
Либо сделать так:
этот пример подходит, но как удалить картинки из папки и из базы а потом саму папку?
связь с таблицей image обычная
что такое внешний ключ я не особо еще понимаю
Суннат Абдухалилов, FileHelper::removeDirectory удаляет директорию со всем её содержимым.
Внешний ключ - foreign key.
Наличие этого ключа удаляет в дочерней таблице все записи, у которых суррогатный ключ равен id записи в родительской таблице.
погуглил засчет внешнего ключа, и добавил строчку. но что то из базы ничего не удаляется
там что то про каскады пишут и миграции, неужто так сложно все?
папка не удаляется, пробовал разные пути делать @web ../web /web web никакой из них не удаляет папку
slo_nik, окей с этим разобрался, Yii::getAlias('@web') не помогло
$path_to_dir = '../web/upload/store/Adverts/Adverts'.$id; это заработало почему-то
не могу теперь удалить картинки из базы по внешнему ключу
$model->unlinkAll('image', true); как использовать это? это я нашел по гуглу
Суннат Абдухалилов, вот как раз надо использовать Yii::getAlias(), меньше проблем будет. Если не работает, то значит Вы что-то не так указали.
Какое отношение $model->unlinkAll('image', true); имеет к внешнему ключу - не знаю.
Достаточно правильно прописать внешний ключ и всё будет работать.
Суннат Абдухалилов, допустим есть две таблицы: Articles(таблица статей) и Images(таблица изображений)
Миграции могут выглядеть так:
Тип и длина значений для id статей и для id_articles должны совпадать. В данном случае это int и длина 11.
На id_articles желательно поставить индекс:
Ну и указать сам внешний ключ:
Всё.
При добавлении статьи, после записи её в базу, необходимо получить id статьи и для каждого изображения, которое принадлежит этой статье заполнить 'id_articles'.
В базе данных, если открыть таблицу изображений, 'id_articles' будет выглядеть как ссылка, при щелчке по этой ссылке Вы попадёте в таблицу 'article's, на нужную статью.
Теперь, при удалении статьи все записи из таблицы изображений, которые принадлежат данной статье, будут удалены.
Остаётся удалить только директорию с нужными изображениями.
Как это сделать Вам уже показали и рассказали.
slo_nik, туплю жёстко
незнаю куда это вставить
$this->addForeignKey('fk-adverts-image_id', '>', 'itemId', 'id', '>', 'CASCADE', 'RESTRICT');
уже пробовал через консоль пример из документации
yii migrate/create angrenka --fields="id:foreignKey(adverts)"
Do not use BaseFileHelper. Use yii\helpers\FileHelper instead.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$mimeAliasesFile | string | The path (or alias) of a PHP file containing MIME aliases. | yii\helpers\BaseFileHelper |
$mimeMagicFile | string | The path (or alias) of a PHP file containing MIME type information. | yii\helpers\BaseFileHelper |
Public Methods
Method | Description | Defined By |
---|---|---|
changeOwnership() | Changes the Unix user and/or group ownership of a file or directory, and optionally the mode. | yii\helpers\BaseFileHelper |
copyDirectory() | Copies a whole directory as another one. | yii\helpers\BaseFileHelper |
createDirectory() | Creates a new directory. | yii\helpers\BaseFileHelper |
filterPath() | Checks if the given file path satisfies the filtering options. | yii\helpers\BaseFileHelper |
findDirectories() | Returns the directories found under the specified directory and subdirectories. | yii\helpers\BaseFileHelper |
findFiles() | Returns the files found under the specified directory and subdirectories. | yii\helpers\BaseFileHelper |
getExtensionsByMimeType() | Determines the extensions by given MIME type. | yii\helpers\BaseFileHelper |
getMimeType() | Determines the MIME type of the specified file. | yii\helpers\BaseFileHelper |
getMimeTypeByExtension() | Determines the MIME type based on the extension name of the specified file. | yii\helpers\BaseFileHelper |
localize() | Returns the localized version of a specified file. | yii\helpers\BaseFileHelper |
normalizePath() | Normalizes a file/directory path. | yii\helpers\BaseFileHelper |
removeDirectory() | Removes a directory (and all its content) recursively. | yii\helpers\BaseFileHelper |
unlink() | Removes a file or symlink in a cross-platform way | yii\helpers\BaseFileHelper |
Protected Methods
Method | Description | Defined By |
---|---|---|
loadMimeAliases() | Loads MIME aliases from the specified file. | yii\helpers\BaseFileHelper |
loadMimeTypes() | Loads MIME types from the specified file. | yii\helpers\BaseFileHelper |
normalizeOptions() | yii\helpers\BaseFileHelper |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
PATTERN_CASE_INSENSITIVE | 32 | yii\helpers\BaseFileHelper | |
PATTERN_ENDSWITH | 4 | yii\helpers\BaseFileHelper | |
PATTERN_MUSTBEDIR | 8 | yii\helpers\BaseFileHelper | |
PATTERN_NEGATIVE | 16 | yii\helpers\BaseFileHelper | |
PATTERN_NODIR | 1 | yii\helpers\BaseFileHelper |
Property Details
The path (or alias) of a PHP file containing MIME aliases.
The path (or alias) of a PHP file containing MIME type information.
Method Details
Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: On Windows, this function fails silently when applied on a regular file.
The path to the file or directory.
The user and/or group ownership for the file or directory. When $ownership is a string, the format is 'user:group' where both are optional. E.g. 'user' or 'user:' will only change the user, ':group' will only change the group, 'user:group' will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. [$myUser, $myGroup] . It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If null , an empty array or an empty string is passed, the ownership will not be changed.
The permission to be set for the file or directory. If null is passed, the mode will not be changed.
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
The source directory
The destination directory
- dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
- fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.
filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true: the directory or file will be copied (the "only" and "except" options will be ignored)
- false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
- null: the "only" and "except" options will determine whether the directory or file should be copied
if unable to open directory
Creates a new directory.
This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.
Path of the directory to be created.
The permission to be set for the created directory.
Whether to create parent directories if they do not exist.
Whether the directory is created successfully
if the directory could not be created (i.e. php error due to parallel changes)
Checks if the given file path satisfies the filtering options.
The path of the file or directory to be checked
The filtering options. See findFiles() for explanations of the supported options.
Whether the file or directory satisfies the filtering options.
Returns the directories found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function (string $path): bool , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory will be returned
- false : the directory will NOT be returned
recursive : boolean, whether the files under the subdirectories should also be looked for. Defaults to true . See findFiles() for more options.
Directories found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Returns the files found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory or file will be returned (the only and except options will be ignored)
- false : the directory or file will NOT be returned (the only and except options will be ignored)
- null : the only and except options will determine whether the directory or file should be returned
Files found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Determines the extensions by given MIME type.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The extensions corresponding to the specified MIME type
Determines the MIME type of the specified file.
This method will first try to determine the MIME type based on finfo_open. If the fileinfo extension is not installed, it will fall back to getMimeTypeByExtension() when $checkExtension is true.
Name of the optional magic database file (or alias), usually something like /path/to/magic.mime . This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.
The MIME type (e.g. text/plain ). Null is returned if the MIME type cannot be determined.
when the fileinfo PHP extension is not installed and $checkExtension is false .
Determines the MIME type based on the extension name of the specified file.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The MIME type. Null is returned if the MIME type cannot be determined.
Loads MIME aliases from the specified file.
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used.
The mapping from file extensions to MIME types
Loads MIME types from the specified file.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The mapping from file extensions to MIME types
Returns the localized version of a specified file.
The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the language code. For example, given the file "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
The original file
The target language that the file should be localized to. If not set, the value of yii\base\Application::$language will be used.
The language that the original file is in. If not set, the value of yii\base\Application::$sourceLanguage will be used.
The matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: On Windows, this function fails silently when applied on a regular file.
The path to the file or directory.
The user and/or group ownership for the file or directory. When $ownership is a string, the format is 'user:group' where both are optional. E.g. 'user' or 'user:' will only change the user, ':group' will only change the group, 'user:group' will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. [$myUser, $myGroup] . It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If null , an empty array or an empty string is passed, the ownership will not be changed.
The permission to be set for the file or directory. If null is passed, the mode will not be changed.
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
The source directory
The destination directory
- dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
- fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.
filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true: the directory or file will be copied (the "only" and "except" options will be ignored)
- false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
- null: the "only" and "except" options will determine whether the directory or file should be copied
if unable to open directory
Creates a new directory.
This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.
Path of the directory to be created.
The permission to be set for the created directory.
Whether to create parent directories if they do not exist.
Whether the directory is created successfully
if the directory could not be created (i.e. php error due to parallel changes)
Checks if the given file path satisfies the filtering options.
The path of the file or directory to be checked
The filtering options. See findFiles() for explanations of the supported options.
Whether the file or directory satisfies the filtering options.
Returns the directories found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function (string $path): bool , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory will be returned
- false : the directory will NOT be returned
recursive : boolean, whether the files under the subdirectories should also be looked for. Defaults to true . See findFiles() for more options.
Directories found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Returns the files found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory or file will be returned (the only and except options will be ignored)
- false : the directory or file will NOT be returned (the only and except options will be ignored)
- null : the only and except options will determine whether the directory or file should be returned
Files found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Determines the extensions by given MIME type.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The extensions corresponding to the specified MIME type
Determines the MIME type of the specified file.
This method will first try to determine the MIME type based on finfo_open. If the fileinfo extension is not installed, it will fall back to getMimeTypeByExtension() when $checkExtension is true.
Name of the optional magic database file (or alias), usually something like /path/to/magic.mime . This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.
The MIME type (e.g. text/plain ). Null is returned if the MIME type cannot be determined.
when the fileinfo PHP extension is not installed and $checkExtension is false .
Determines the MIME type based on the extension name of the specified file.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The MIME type. Null is returned if the MIME type cannot be determined.
Loads MIME aliases from the specified file.
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used.
The mapping from file extensions to MIME types
Loads MIME types from the specified file.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The mapping from file extensions to MIME types
Returns the localized version of a specified file.
The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the language code. For example, given the file "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
The original file
The target language that the file should be localized to. If not set, the value of yii\base\Application::$language will be used.
The language that the original file is in. If not set, the value of yii\base\Application::$sourceLanguage will be used.
The matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned.
Кэширование данных заключается в сохранении некоторой переменной PHP в кэше и её последующем извлечении. Оно является основой для расширенных возможностей, таких как кэширование запросов и кэширование страниц.
Кэширование данных (Полное руководство по Yii 2.0) здесь
Abstract Class yii\caching\Cache (API Documentation) здесь
По-умолчанию кэш в Yii2 ( Advanced ) разделён и сохраняется в соответствующие каталоги: backend\runtime\cache и frontend\runtime\cache . Убедиться в этом можно, вызвав команду Yii::$app->cache из frontend или backend, соответственно.
Для того, чтобы иметь возможность работать с кэшем другого приложения (например из backend удалить кэш frontend) можно указать для этих приложений общее хранилище. Весь кэш приложений будем хранить в каталоге common , затем будем удалять нужный нам кэш (в том числе кэш frontend) из админки.
В файле common\config\main.php :
В приложении одновременно можно использовать разные способы хранения кэша. Об остальных поддерживаемых хранилищах читайте в документации, я же буду использовать (для примера) только yii\caching\FileCache .
Кэширование произвольных данных (результаты выборки, данные внутри виджетов и тп.)
Начиная с версии 2.0.11, компонент кэширования предоставляет метод getOrSet() , который упрощает код при получении, вычислении и сохранении данных. Приведённый ниже код делает в точности то же самое, что и код в предыдущем примере:
Кэширование фрагментов
Кэширование фрагментов относится к кэшированию фрагментов страницы. Обычно кэширование фрагментов используйтся в представлении:
Срок хранения duration . По умолчанию, если срок хранения не указан $defaultDuration = 0 . Это означает то, что время хранения бесконечен.
Вариации variations на примере кэширования виджета категорий:
Кэширование запросов
Кэширование запросов - это специальная функция, построенная на основе кэширования данных. Она предназначена для кэширования результатов запросов к базе данных.
В пределах cache() вы можете отключить кэширование запроса. В этом случае вы можете использовать [[yii\db\Connection::noCache()]] :
Если вы просто хотите использовать кэширование для одного запроса, вы можете вызвать [[yii\db\Command::cache()]] при построении команды:
Можете использовать [[yii\db\Command::noCache()]] для отключения кэширования запросов для одной команды:
Кэширование страниц
Кэширование страниц — это кэширование всего содержимого страницы на стороне сервера. Когда эта страница будет запрошена, сервер вернет её из кэша вместо того чтобы генерировать её заново.
Приведённый код задействует кэширование только для действия view . Содержимое страницы кэшируется максимум на 1 час и варьируется в зависимости от текущего языка приложения. Кэшированная страница должна быть признана просроченной, если поле update_at изменилось.
Кэширование страниц очень похоже на кэширование фрагментов. В обоих случаях поддерживаются параметры duration (продолжительность), dependencies (зависимости), variations (вариации), и enabled (включен). Главное отличие заключается в том, что кэширование страницы реализовано в виде фильтра действия, а кэширование фрагмента в виде виджета.
Очистка кэша
Для очистки всего кэша, вы можете вызвать [[yii\caching\Cache::flush()]] .
Очистить кэш из консоли можно вызвав yii cache/flush .
- yii cache : отображает список доступных кэширующих компонентов приложения
- yii cache/flush cache1 cache2 : очищает кэш в компонентах cache1, cache2 (можно передать несколько названий компонентов кэширования, разделяя их пробелом)
- yii cache/flush-all : очищает кэш во всех кэширующих компонентах приложения
Внимание!
Консольное приложение использует отдельный конфигурационный файл по умолчанию. Для получения должного результата, убедитесь, что в конфигурациях консольного и веб-приложения у вас одинаковые компоненты кэширования.
Очистить кэш из контроллера:
Очистить кэш фрагмента по ключу:
Автоматическое удаление кэша при обновлении записи в базе данных
Когда в БД вносятся изменения (добавление, редактирование, удалении записи в админке), данные в кэше становятся неактуальными. В этом случае можно к модели, которая отвечает за нужную таблицу подключить поведение с событиями для ActiveRecord ( EVENT_AFTER_INSERT , EVENT_AFTER_UPDATE , EVENT_AFTER_DELETE ), которые при каждом срабатывании будут удалять нужный кэш.
файл CachedBehavior.php в папке common\components\behaviors :
Подключаем поведение к нужной модели:
Автоматическое удаление кэша при выполнении действий контроллера
Код, указанный выше обновляет кэш при действиях, указаных в поведении CachedBehavior . Данное поведение привязано к модели, которая в свою очередь занимается ещё выборкой записей. Такой подход в данном случае не очень интнресный, поэтому мы воспользуемся методом удаления кэша из контроллера. Плюсом такого метода является то, что мы можем на нужный нам контроллер навесить нужные события и в конечном итоге модель будет заниматься только логикой (выборка данных и тд), а контроллер по событию каких-либо действий с записями удалять нужный кэш.
Добавляем поведение в контроллер (у меня это backend\controllers\CategoryController.php ):
Удаление кэша по тэгу
Class yii\caching\TagDependency (API Documentation) здесь
При кэшировании данных мы указываем зависимость:
В нужном нам контроллере и нужном экшене (после сохранения модели):
На гитхабе нашёл вот такой trait. Сам не пробовал использовать. Кому интересно, посмотрите.
Простой сервис для удаления кэша по тэгу
Пример очень простого сервиса по по очистке кэша по тэгу. Дело в том, что лучше бы не вызывать постоянно $cache = Yii::$app->cache; , а работать с объектом кэша напрямую через некий сервис, который будет в нужный нам момент очищать кэш по тэгу.
Там где получаем данные (модель или лучше отдельный репозиторий для получения данных):
Обертка для кэширования данных в Yii2
Можно кэширование обернуть в функцию и избавить себя от многократного писания переменных $data, $cache, $key. Тем более, если рядом используется кэширование нескольких фрагментов данных.
Здесь я кратким конспектом рассмотрел основные принципы кэширования в Yii2. Всё, о чем не упомянуто здесь, вы можете найти по ссылкам выше.
Читайте также: