October cms очистить кэш
October CMS includes several command-line interface (CLI) commands and utilities that allow you to manage various aspects of the platform, as well as speed up the development process. The console commands are based on Laravel's Artisan
The october:update command will request updates from the October gateway. It will update the core application and plugin files, then perform a database migration.
The october:migrate command will perform a database migration, creating database tables and executing seed scripts, provided by the system and plugin version history. The migration command can be run multiple times, it will only execute a migration or seed script once, which means only new changes are applied.
The --rollback option will reverse all migrations, dropping database tables and deleting data. Care should be taken when using this command. The plugin refresh command is a useful alternative for debugging a single plugin.
The october:passwd command allows the password of a backend administrator to be changed via the command line. This is useful if you are locked out of your October CMS install, or for changing the password for the default administrator account.
For the first argument you may pass either the login name or email address. For the second argument you may optionally pass the desired password, otherwise you will be prompted to enter one.
October CMS includes these commands for managing your project.
project:sync installs all plugins and themes belonging to a project.
project:set sets the license key for the current installation.
October CMS includes a number of commands for managing plugins.
plugin:install - downloads and installs the plugin by its name. The next example will install a plugin called AuthorName.PluginName.
You may install a plugin from a remote source using the --from option.
Use the --want option to specify a target branch or version.
Use the --oc option if your package name has the oc prefix.
plugin:check - performs a system wide check of installed plugin dependencies. This command will spin over every theme and plugin that is currently installed and check to see if its dependencies are also installed. If it finds any missing requirements, it will attempt to install them.
plugin:refresh - destroys the plugin's database tables and recreates them. This command is useful for development.
Use the --rollback option to only destroy the database tables without recreating them.
You may also specify a version number with the --rollback option to stop at a specified version.
plugin:list - Displays a list of installed plugins and their version numbers.
plugin:disable - Disable an existing plugin.
plugin:enable - Enable a disabled plugin.
plugin:remove - destroys the plugin's database tables and deletes the plugin files from the filesystem.
October includes a number of commands for managing themes.
theme:install - download and install a theme from the Marketplace
(opens new window) . The following example will install the theme in /themes/authorname-themename
You may install a theme from a remote source using the --from option.
Use the --want option to specify a target branch or version.
Use the --oc option if your package name has the oc prefix.
theme:check - performs a system wide check of themes to see if they should be flagged read-only and protected from changes. This command will spin over every theme and check if it has been installed with composer, if so, a theme lock file is added and a child theme is created.
theme:list - list installed themes.
theme:use - switch the active theme. The following example will switch to the theme in /themes/rainlab-vanilla
theme:remove - delete a theme. The following example will delete the directory /themes/rainlab-vanilla
theme:copy - duplicates an existing theme to create a new one, including the creation of child themes.
The following command creates a new theme called demo-copy from the source theme demo by copying the directory and its contents. The .themelock file will be removed during this process.
To create a child theme that inherits the parent theme, specify the --child option.
If using database-driven themes, you may sync the database changes to the filesystem with the --import-db option.
To delete all the database templates at the same time, use the --purge-db option.
October CMS includes a number of utility commands.
cache:clear - clears the application, twig and combiner cache directories. Example:
october:fresh - removes the demo theme and plugin that ships with October CMS.
october:mirror - will mirror all asset and resource files to the public folder using symbolic linking.
If you want to specify a custom folder, you can pass it as the second argument, which is relative to the base directory.
october:util - a generic command to perform general utility tasks, such as cleaning up files or combining files. The arguments passed to this command will determine the task used.
Outputs combined system files for JavaScript (js), StyleSheets (less), client side language (lang), or everything (assets).
To combine without minification, pass the --debug option.
This will execute the command git pull on all theme and plugin directories.
Deletes all generated thumbnails in the uploads directory.
Deletes files in the uploads directory that do not exist in the system_files table.
Deletes records in system_files table that do not belong to any other model.
Октябрь предоставляет унифицированное API для различных систем кэширования. Настройки кэша содержатся в файле config/cache.php . Там же Вы можете указать драйвер, который будет использоваться для кэширования. Многие популярные системы, такие как Memcached и Redis поддерживатся "из коробки".
Файл с настройками также содержит множество других параметров, которые в нём же документированы, поэтому обязательно ознакомьтесь с ними. По умолчанию OctoberCMS настроен для использования драйвера file , который хранит упакованные объекты кэша в файловой системе. Для больших приложений рекомендуется использование систем кэширования в памяти - таких как Memcached или APC.
Утилиты
October включает в себя ряд дополнительных команд.
Требования
База данных
Драйвер кэша database использует базу данных вместо файловой системы. Структура базы данных уже создана, поэтому для его использования Вам больше не нужно ничего настраивать.
Memcached
Вам нужно установить и настроить Memcached PECL package для того, чтобы испльзовать Memcached.
Конфигурация по умолчанию использует TCP/IP на основе Memcached::addServer:
Вы также можете указать параметр host . Тогда параметр port должен быть равен 0 :
Redis
Вы должны установить Drivers plugin перед тем, как использовать драйвер Redis.
Файл с настройками находится в config/database.php . Внутри этого файла вы увидите массив redis , содержащий серверы Redis, используемые вашим приложением:
Вы можете определить массив options , чтобы указать набор Predis client options.
Если Ваш сервер Redis требует аутентификацию, то Вы можете добавить параметр password в файл с настройками.
Strings
Использование кэша
В то время как бОльшая часть логики кэширования скрыта внутри Октября, фасад Cache предоставляет некоторые простые методы для кэширования ваших собственных данных.
Установка темы
theme:install - скачивает и устанавливает тему из Маркетплейса.
Укажите название папки в качестве второго аргументы для установки темы в произвольную папку:
Удаление темы
theme:remove - удаляет тему:
Paths
Path Symbols
Path prefix symbols can be used to create a dynamic path. For example, a path beginning with ~/ will create a path relative to the application:
These symbols are supported for creating dynamic paths:
Symbol | Description |
---|---|
$ | Relative to the plugins directory |
~ | Relative to the application directory |
app_path()
The app_path function returns the fully qualified path to the app directory:
You may also use the app_path function to generate a fully qualified path to a given file relative to the application directory:
base_path()
The base_path function returns the fully qualified path to the project root:
You may also use the base_path function to generate a fully qualified path to a given file relative to the application directory:
config_path()
The config_path function returns the fully qualified path to the application configuration directory:
database_path()
The database_path function returns the fully qualified path to the application's database directory:
plugins_path()
The plugins_path function returns the fully qualified path to the application plugin directory:
public_path()
The public_path function returns the fully qualified path to the public directory:
storage_path()
The storage_path function returns the fully qualified path to the storage directory:
You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:
temp_path()
The temp_path function returns the fully qualified path to a writable directory for temporary files:
themes_path()
The themes_path function returns the fully qualified path to the themes directory:
uploads_path()
The uploads_path function returns the fully qualified path to the application uploads directory:
Требования
База данных
Драйвер кэша database использует базу данных вместо файловой системы. Структура базы данных уже создана, поэтому для его использования Вам больше не нужно ничего настраивать.
Memcached
Вам нужно установить и настроить Memcached PECL package для того, чтобы испльзовать Memcached.
Конфигурация по умолчанию использует TCP/IP на основе Memcached::addServer:
Вы также можете указать параметр host . Тогда параметр port должен быть равен 0 :
Redis
Вы должны установить Drivers plugin перед тем, как использовать драйвер Redis.
Файл с настройками находится в config/database.php . Внутри этого файла вы увидите массив redis , содержащий серверы Redis, используемые вашим приложением:
Вы можете определить массив options , чтобы указать набор Predis client options.
Если Ваш сервер Redis требует аутентификацию, то Вы можете добавить параметр password в файл с настройками.
Очистка кэша
cache:clear - очищает кэш приложения. Пример:
Получение элементов из кэша
Метод get фасада Cache используется для получения элементов из кэша. Если элемент не существует, то метод вернет null . Второй аргумент указывает значение по умолчанию:
Вы даже можете передать значение Closure в качестве значения по умолчанию. Результат Closure будет возвращен, если в кеше указанный элемент не существует:
Проверка существования элемента в кэше
Увеличение / Уменьшение значений
Увеличение числового значения:
Уменьшение числового значения:
Retrieve or update
Иногда Вам может быть нужно получить элемент из кэша или сохранить его там, если он не существует. Вы можете сделать это методом Cache::remember :
Вы также можете совместить методы remember и forever :
Retrieve and delete
Если Вы хотите получить элемент из кэша и затем удалить его, вы можете воспользоваться методом pull :
Arrays
array_add()
The array_add function adds a given key / value pair to the array if the given key doesn't already exist in the array:
array_divide()
The array_divide function returns two arrays, one containing the keys, and the other containing the values of the original array:
array_dot()
The array_dot function flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth:
array_except()
The array_except method removes the given key / value pairs from the array:
array_first()
The array_first method returns the first element of an array passing a given truth test:
A default value may also be passed as the third parameter to the method. This value will be returned if no value passes the truth test:
array_flatten()
The array_flatten method will flatten a multi-dimensional array into a single level.
array_forget()
The array_forget method removes a given key / value pair from a deeply nested array using "dot" notation:
array_get()
The array_get method retrieves a value from a deeply nested array using "dot" notation:
The array_get function also accepts a default value, which will be returned if the specific key is not found:
array_only()
The array_only method will return only the specified key / value pairs from the given array:
array_pluck()
The array_pluck method will pluck a list of the given key / value pairs from the array:
array_pull()
The array_pull method returns and removes a key / value pair from the array:
array_set()
The array_set method sets a value within a deeply nested array using "dot" notation:
array_sort()
array_sort_recursive()
The array_sort_recursive function recursively sorts the array using the sort function:
array_where()
The head function simply returns the first element in the given array:
The last function returns the last element in the given array:
Miscellaneous
Composer
Используйте команду create-project , чтобы закачать исходный код в папку /myoctober:
После чего откройте файл config/cms.php и внесите следующие изменения:
Используйте команду composer update для обновления системы.
Примечание: Composer будет искать внутри плагинов зависимости, которые будут включены в обновления.
Управление плагинами
October включает в себя ряд команд для управления плагинами.
Arrays
Установка системы
Команда october:install поможет вам установить OctoberCMS на сервер:
После чего Вы можете внести необходимые изменения в config/app.php и config/cms.php.
Зеркальная копия папки public
october:mirror - создает зеркальную копию папки public, используя symbolic linking (см. Настройка папки public).
October includes a variety of "helper" PHP functions. Many of these functions are used internally by October itself, however, you are free to use them in your own plugins and applications if you find them useful.
Обновление системы
Команда october:update обновит файлы ядра, плагины и внесет необходимые изменения в базу данных.
Примечание: Если Вы использовали composer для установки, то ядро приложение не обновится автоматически! Используйте сначала команду composer update , а уже после php artisan october:update .
Обновление плагина
plugin:refresh - удаляет таблицы плагина и заново их создает. Эта команда полезна при разработке.
Включение темы
theme:use - устанавливает активную тему:
Strings
camel_case()
The camel_case function converts the given string to camelCase :
class_basename()
The class_basename returns the class name of the given class with the class' namespace removed:
The e function runs htmlentities over the given string:
ends_with()
The ends_with function determines if the given string ends with the given value:
snake_case()
The snake_case function converts the given string to snake_case :
str_limit()
The str_limit function limits the number of characters in a string. The function accepts a string as its first argument and the maximum number of resulting characters as its second argument:
starts_with()
The starts_with function determines if the given string begins with the given value:
str_contains()
The str_contains function determines if the given string contains the given value:
str_finish()
The str_finish function adds a single instance of the given value to a string:
str_is()
The str_is function determines if a given string matches a given pattern. Asterisks may be used to indicate wildcards:
str_plural()
The str_plural function converts a string to its plural form. This function currently only supports the English language:
str_random()
The str_random function generates a random string of the specified length:
str_singular()
The str_singular function converts a string to its singular form. This function currently only supports the English language:
str_slug()
The str_slug function generates a URL friendly "slug" from the given string:
studly_case()
The studly_case function converts the given string to StudlyCase :
trans()
The trans function translates the given language line using your localization files:
trans_choice()
The trans_choice function translates the given language line with inflection:
Удаление плагина
plugin:remove - удаляет таблицы и все файлы плагина.
Установка
Установка консоли может быть выполнена при помощи системы или Composer. Если вы планируете использовать базу данных, убедитесь после установки в работе команды install.
Миграция
Команда october:up внесет необходимые изменения в базу данных: создаст таблицы и добавит новые значения, указанные в файле version.yaml.
Команда october:down вернет все изменения обратно. Новые таблицы, как и новые значения в них, будут удалены. php artisan october:down
Управление темами
October включает в себя ряд команд для управления темами.
Удалить Демо
october:fresh - удаляет демо темы и плагина, которые устанавливаются по умолчанию.
Miscellaneous
asset()
config()
The config function gets the value of a configuration variable. The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access. A default value may be specified and is returned if the configuration option does not exist:
The config helper may also be used to set configuration variables at runtime by passing an array of key / value pairs:
The dd function dumps the given variable and ends execution of the script:
The env function gets the value of an environment variable or returns a default value:
The get function obtains an input item from the request, restricted to GET variables only:
input()
The input function obtains an input item from the request:
The post function obtains an input item from the request, restricted to POST variables only:
redirect()
The redirect function return an instance of the redirector to do redirect responses:
request()
The request function returns the current request instance:
response()
The response function creates a response instance or obtains an instance of the response factory:
route()
The route function generates a URL for the given named route:
If the route accepts parameters, you may pass them as the second argument to the method:
secure_asset()
trace_log()
The trace_log function writes a trace message to the log file.
The function supports passing exceptions, arrays and objects:
You may also pass multiple arguments to trace multiple messages:
trace_sql()
The trace_sql function enables database logging and begins to monitor all SQL output.
October includes several command-line interface (CLI) commands and utilities that allow to install October, update it, as well as speed up the development process. The console commands are based on Laravel's Artisan
Console installation can be performed using the native system or with Composer
(opens new window) to manage dependencies. Either approach will download the October application files and can be used right away. If you plan on using a database, be sure to run the install command after installation.
Run this in your terminal to get the latest copy of October:
Or if you don't have curl:
Note: The quick start install will install October CMS v1.0 that uses the Laravel 5.5 Framework (opens new window) .
Download the application source code by using create-project in your terminal. The following command will install to a directory called /myoctober.
When updating October, use the composer update command as normal before performing a database migration.
Composer is configured to look inside plugin directories for composer dependencies and these will be included in updates.
Note: The composer command will install October CMS v1.1 that uses the Laravel 6 Framework (opens new window) .
The october:install command will guide you through the process of setting up OctoberCMS for the first time. It will ask for the database configuration, application URL, encryption key and administrator details.
You also may wish to inspect config/app.php and config/cms.php to change any additional configuration.
Note: You cannot run october:install after running october:env . october:env takes the existing configuration values and puts them in the .env file while replacing the original values with calls to env() within the configuration files. october:install cannot now replace those calls to env() within the configuration files as that would be overly complex to manage.
The october:update command will request updates from the October gateway. It will update the core application and plugin files, then perform a database migration.
IMPORTANT: If you are using using composer do NOT run this command without first making sure that cms.disableCoreUpdates is set to true. Doing so will cause conflicts between the marketplace version of October and the version available through composer. In order to update the core October installation when using composer run composer update instead.
The october:up command will perform a database migration, creating database tables and executing seed scripts, provided by the system and plugin version history. The migration command can be run multiple times, it will only execute a migration or seed script once, which means only new changes are applied.
The inverse command october:down will reverse all migrations, dropping database tables and deleting data. Care should be taken when using this command. The plugin refresh command is a useful alternative for debugging a single plugin.
The october:passwd command will allow the password of a Backend user or administrator to be changed via the command-line. This is useful if someone gets locked out of their October CMS install, or for changing the password for the default administrator account.
You may provide the username/email and password as both the first and second argument, or you may leave the arguments blank, in which case the command will be run interactively.
October includes a number of commands for managing plugins.
plugin:install - downloads and installs the plugin by its name. The next example will install a plugin called AuthorName.PluginName. Note that your installation should be bound to a project in order to use this command. You can create projects on October website, in the Account / Projects
plugin:refresh - destroys the plugin's database tables and recreates them. This command is useful for development.
plugin:rollback - Rollback the specified plugin's migrations. The second parameter is optional, if specified the rollback process will stop at the specified version.
plugin:list - Displays a list of installed plugins.
plugin:disable - Disable an existing plugin.
plugin:enable - Enable a disabled plugin.
plugin:remove - destroys the plugin's database tables and deletes the plugin files from the filesystem.
October includes a number of commands for managing themes.
theme:install - download and install a theme from the Marketplace
(opens new window) . The following example will install the theme in /themes/authorname-themename
If you wish to install the theme in a custom directory, simply provide the second argument. The following example will download AuthorName.ThemeName and install it in /themes/my-theme
theme:list - list installed themes. Use the -m option to include popular themes in the Marketplace.
theme:use - switch the active theme. The following example will switch to the theme in /themes/rainlab-vanilla
theme:remove - delete a theme. The following example will delete the directory /themes/rainlab-vanilla
theme:sync - Sync a theme's content between the filesystem and database when cms.databaseTemplates is enabled.
By default the theme that will be synced is the currently active one. You can specify any theme to sync by passing the desired theme's code:
By default the sync direction will be from the database to the filesytem (i.e. you're syncing changes on a remote host to the filesystem for tracking in a version control system). However, you can change the direction of the sync by specifying --target=database . This is useful if you have changed the underlying files that make up the theme and you want to force the site to pick up your changes even if they have made changes of their own that are stored in the database.
By default the command requires user interaction to confirm that they want to complete the sync (including information about the amount of paths affected, the theme targeted, and the target & source of the sync). To override the need for user interaction (i.e. if running this command in a deploy / build script of some sort) just pass the --force option:
Unless otherwise specified, the command will sync all the valid paths (determined by the Halcyon model instances returned to the system.console.theme.sync.getAvailableModelClasses event) available in the theme. To manually specify specific paths to be synced pass a comma separated list of paths to the --paths option:
October includes a number of utility commands.
cache:clear - clears the application, twig and combiner cache directories. Example:
october:fresh - removes the demo theme and plugin that ships with October.
october:mirror - creates a mirrored copy of the public files needed to serve the application, using symbolic linking. This command is used when setting up a public folder.
Note: By default the symlinks created will be absolute symlinks, to create them as relative symlinks instead include the --relative option:
october:env - changes common configuration values to DotEnv syntax.
october:util - a generic command to perform general utility tasks, such as cleaning up files or combining files. The arguments passed to this command will determine the task used.
Outputs combined system files for JavaScript (js), StyleSheets (less), client side language (lang), or everything (assets).
To combine without minification, pass the --debug option.
This will execute the command git pull on all theme and plugin directories.
Запись элементов в кэш
Запись нового элемента в кэш
Использование объекта Carbon для установки времени жизни кэша
Метод add возвращает true , если производится запись элемента в кэш. Иначе, если элемент уже есть в кэше, возвращается false :
OctoberCMS включает в себя несколько консольных команд и утилит, основанных на инструменте Laravel - Artisan, которые позволяют установить систему, обновить ее, а также ускорить процесс разработки. Вы можете создавать свои команды или использовать уже существующие.
Быстрый старт
Введите эту строчку в терминал, чтобы получить последнюю копию October:
Установка плагина
plugin:install - скачивает и устанавливает указанный плагин.
Настройка и Поддержка
Paths
Список тем
theme:list - список установленных тем. Используйте параметр e -m, чтобы посмотреть популярные темы в Маркетплейсе.
Читайте также: