php artisan route cache

Laravel Framework Russian Community

Введение

Простейшие контроллеры

Вот пример простейшего класса контроллера:

Привязка «действия» (action) к определенному маршруту происходит так:

Примечание: Все контроллеры должны наследоваться от базового класса контроллера.

Контроллеры и пространства имён

По умолчанию, класс RouteServiceProvider загружает все маршруты из файла routes.php в группу с «корневым» пространством имён.

Именованные роуты с контроллерами

Как и в случае с обработчиками-замыканиями, вы можете присвоить имя этому роуту:

Ссылки на «действия» контроллера

Если вы хотите создавать ссылки на «действие» контроллера, используя относительные имена классов, то сначала нужно зарегистрировать «корневое» пространство имён с контроллерами:

Для непосредственного создания ссылки на «действие» контроллера, воспользуйтесь функцией-помощником action :

Получить имя «действия», которое выполняется в данном запросе, можно методом currentRouteAction :

Использование посредников с контроллерами

Посредники могут быть привязаны к маршрутам следующим образом:

Так же, вы можете указывать их и в конструкторе самого контроллера:

Единые контроллеры

Laravel позволяет вам легко создавать один маршрут для обработки всех действий контроллера. Для начала, зарегистрируйте маршрут методом Route::controller :

Если имя действия вашего контроллера состоит из нескольких слов вы можете обратиться к нему по URI, используя синтаксис с дефисами (-). Например, данное действие в нашем классе UserController будет доступно по адресу users/admin-profile :

Назначение имён

RESTful ресурс-контроллеры

Для создания контроллера выполните следующую консольную команду:

Теперь мы можем зарегистрировать его как ресурс-контроллер:

Действия, обрабатываемые ресурс-контроллером:

VerbПутьДействиеИмя маршрута
GET/photoindexresource.index
GET/photo/createcreatephoto.create
POST/photostorephoto.store
GET/photo/

showphoto.show
GET/photo//editeditphoto.edit
PUT/PATCH/photo/

updatephoto.update
DELETE/photo/

destroyphoto.destroy

Настройка маршрутов в ресурс-контроллерах

Иногда вам понадобится обрабатывать только часть всех возможных действий:

По умолчанию, все действия ресурс контроллеров имеют имя в формате «ресурс.действие». Однако, вы можете изменить эти имена, используя массив names в опциях:

Обработка наследуемых ресурс-контроллеров

Этот маршрут зарегистрирует «унаследованный» контроллер ресурсов, который может принимать URL такие как: photos//comments/ .

Добавление дополнительных маршрутов к ресурс контроллерам

Если вдруг необходимо добавить дополнительные маршруты к уже существующим маршрутам ресурс-контроллера, необходимо зарегистрировать эти маршруты перед вызовом метода Route::resource :

Внедрение зависимостей в контроллерах

Внедрение зависимостей в конструкторе

Сервис-контейнер используется для поиска и получения всех контроллеров. За счёт этого вы можете указать любые зависимости в качестве аргументов конструктора вашего контроллера, в том числе и любой контракт:

Внедрение зависимостей в методах контроллеров

Точно так же можно указывать зависимости для любого метода контролера. Например, давайте укажем Request как зависимость метода store :

Если метод контроллера так же ожидает какие-либо данные из маршрута, то можно просто указать их после всех зависимостей:

Примечание: Внедрение зависимостей в методы контроллера полностью дружат с механизмом связанных моделей. Сервис-контейнер определит, какие из аргументов должны быть связаны с моделями, а какие должны быть внедрены.

Кэширование маршрутов

Если ваше приложение использует только контроллеры для обработки маршрутов, вы можете использовать кэширование маршрутов, которое кардинально уменьшает время, требуемое на разбор и регистрацию всех маршрутов внутри приложения.

В некоторых случаях прирост скорости может достигнуть 100 раз! Для включения кэширования просто выполните Artisan-команду route:cache :

Для удаления кэша маршрутов без генерации нового используется Artisan-команда route:clear :

Источник

Laravel Artisan Cache Commands Explained

Often times, when you are in the middle of developing a Laravel application, you may find that the changes you made in your code are not reflecting well on the application when testing.

Usually, the case is most likely caused by caching applied by the Laravel framework.

Here are some of the common commands you can run in your terminal to alleviate the issue.

❗️ Make sure you are running them in the context of your application. Meaning, your terminal is currently in the same directory as your Laravel application.

1. Configuration Cache

Caching configuration helps with combining all of the configuration options for your application into a single file which will be loaded quickly by the framework.

Clearing Configuration Cache

Exit fullscreen mode

If you want to quickly reset your configuration cache after clearing them, you may instead run the following command:

Exit fullscreen mode

Caching your configuration will also help clear the current configuration cache. So it helps save your time without having to run both commands.

2. Route Caching

Caching your routes will drastically decrease the amount of time it takes to register all of your application’s routes. When you add a new route, you will have to clear your route cache for the new route to take effect.

Clearing Route Cache

The following command will clear all route cache in your application:

Exit fullscreen mode

To cache your routes again, simply run the following command:

Exit fullscreen mode

Again, running the above command alone is enough to clear your previous route cache and rebuild a new one.

3. Views Caching

Views are cached into compiled views to increase performance when a request is made. By default, Laravel will determine if the uncompiled view has been modified more recently than the compiled view, before deciding if it should recompile the view.

Clearing View Cache

However, if for some reason your views are not reflecting recent changes, you may run the following command to clear all compiled views cache:

Exit fullscreen mode

In addition, Laravel also provides an Artisan command to precompile all of the views utilized by your application. Similarly, the command also clears the view cache before recompiling a new set of views:

Exit fullscreen mode

4. Events Cache

If you are using Events in your Laravel application, it is recommended to cache your Events, as you likely do not want the framework to scan all of your listeners on every request.

Clearing Events Cache

When you want to clear your cached Events, you may run the following Artisan command:

Exit fullscreen mode

Likewise, caching your Events also clear any existing cache in the framework before a new cache is rebuilt:

Exit fullscreen mode

5. Application Cache

Using Laravel’s Cache is a great way to speed up frequently accessed data in your application. While developing your application involving cache, it is important to know how to flush all cache correctly to test if your cache is working properly.

Clearing Application Cache

To clear your application cache, you may run the following Artisan command:

Exit fullscreen mode

❗️ This command will NOT clear any config, route, or view cache, which are stored in /bootstrap/cache/ directory.

6. Clearing All Cache

Laravel provides a handy Artisan command that helps clear ALL the above caches that we have covered above. It is a convenient way to reset all cache in your application, without having to run multiple commands introduced before.

To clear all Laravel’s cache, just run the following command:

Exit fullscreen mode

As you can read from the terminal feedback, all cache types that existed in your Laravel application will be cleared entirely, except Events cache.

🎁 Bonus

If the above Laravel’s Artisan commands don’t seem to resolve the issue you are facing, you may need to look at other related environments in your project that may be causing it.

When building a Laravel project, it is common to employ the Composer Dependency Manager for PHP, as well as NPM for any JavaScript library that might be needed in your project. We just have to take note that both package managers are using some form of caching for performance improvements.

Clearing Composer Cache

Sometimes, a new package you just installed via Composer doesn’t appear to be working at all. Or a new project you just cloned from a repository doesn’t seem to be running correctly.

Such issues are usually caused by classmap error from a newly installed library class, or the cached version of a particular library does not match with the ones required by the project codebase you just cloned. In such a situation, you need to update the PHP autoloader by running the following command:

Exit fullscreen mode

As well as any of the following variations(they all achieve the same purpose of deleting all content from Composer’s cache directories):

Источник

How to clear Laravel route caching on server

This is regarding route cache on localhost

About Localhost

I have 2 routes in my route.php file. Both are working fine. No problem in that. I was learning route:clear and route:cache and found a small problem below.

if I comment any one route in my route.php file and then run below command

This will keep the route disabled because the route list is in cache now. Now, go to route.php file and try to remove commented route and then try to run that enabled url. still it will show 404 because I need to remove cache by using below command

So far everything is understood in localhost. No problem in that.

After deploying on shared hosting server on godaddy

Question : How can I remove the route cache on server?

4 Answers 4

If you want to remove the routes cache on your server, remove this file:

And if you want to update it just run php artisan route:cache and upload the bootstrap/cache/routes.php to your server.

If you are uploading your files through GIT from your local machine then you can use the same command you are using in your local machine while you are connected to your live server using BASH or something like.You can use this as like you use locally.

php artisan route cache. Смотреть фото php artisan route cache. Смотреть картинку php artisan route cache. Картинка про php artisan route cache. Фото php artisan route cache

For your case solution is :

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can’t see any more change in my view, but at last I did resolve my problem using laravel command so, let’s see i added several command for clear cache from view, route, config etc.

Источник

php artisan make:auth conflicts with route:cache ‘Unable to prepare route [api/user] for serialization. Uses Closure.’ #22034

Comments

lvbeck commented Nov 9, 2017

Description:

I use ‘php artisan make:auth’ command to scaffold routes and views for authentication, however when I run ‘php artisan route:cache’, an error will occur:

Steps To Reproduce:

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

haakym commented Nov 9, 2017

Can you check your routes/web.php and routes/api.php for closures.

Laravel comes with default route closure in routes/web.php :

if you remove that then try again it should work I reckon.

lvbeck commented Nov 9, 2017

@haakym thanks, I know it will works if I remove above code in routes/api.php, but is there any side effect to do so?
will the route «api/user» still working?

lvbeck commented Nov 9, 2017

I did found a serious side effect after the changes,

now, I can run ‘php artisan route:cache’ with no problem, but I got a runtime exception:

themsaid commented Nov 9, 2017

Please ask on the forums, this repo is for bug reporting only. You can use https://laracasts.com/discuss or https://laravel.io/forum which are forums with a very large community of developers helping each other.

xkovacikm commented Apr 25, 2018

@themsaid Please, stop throwing responsibility on the others. This is definitely a bug.
Laravel offers predefined code in routes/api.php

which is unabled to be processed by:

php artisan route:cache

This definitely should be fixed.

themsaid commented Apr 25, 2018

@xkovacikm feel free to open a PR

feribg commented Apr 28, 2018

Why is this closed? This is an obvious bug.

devcircus commented Apr 29, 2018

Straight from the documentation:

IF your application is EXCLUSIVELY using controller based routes, you should take advantage of Laravel’s route cache.
Closure based routes cannot be cached. To use route caching, you must convert any Closure routes to controller classes.

xkovacikm commented Apr 29, 2018

Yeah. You’re right is written in documentation. But that isn’t the problem.
Problem is, that some Laravel developer written some code which can’t be compiled if someone wants to cache routes.

If Laravel contains code which can’t be compiled, it’s bug and should be fixed.

feribg commented Apr 29, 2018

@devcircus Im not really involved with laravel I just raise the point because I downloaded the framework, enabled a built in feature—> auth and it broke another built in and critical feature of any production deployment, notably clearing the cache. So wether the default way auth routes come out of the box changes or how the cache clearing changes doesn’t matter really but a framework shouldn’t break a production deployment once a core built in module is enabled with the default config in my opinion. If that’s not your opinion I understand.

devcircus commented Apr 30, 2018

The «auth» method has no effect on route caching. The method (below) only adds controller based routes, which are perfectly cacheable.

The issue is that in the laravel/laravel skeleton app, there are a couple of sample Closure routes included in the api and web routes files. These routes are present for example purposes. Route caching is a documented optional feature. This documentation makes it clear that if you want to cache your routes, you’ll need to be sure to use the controller based approach for it to work.

There are many features in Laravel that don’t just «work» out-of-the-box. You can change your «session», «cache» and/or «queue» handling to use redis. However if you just change this to redis and expect it to just work, you’ll be disappointed, as there are other libraries that need to be pulled in first. I just don’t believe that we can expect everything provided by the framework to just work. Sometimes you have to do a little research and make sure everything is set up correctly first.

haakym commented May 1, 2018 •

@xkovacikm IMO I don’t think this can be called a bug. Sure, it’s annoying that if you want to cache your routes and you don’t remove the pre-defined closure routes it won’t work, but it’s a matter of removing them to get it to work. As @themsaid said a PR can be made which I think would be a good way of pursuing this discussion further.

vipertecpro commented Aug 25, 2018

Источник

The Current

Thought Leadership

Thought Leadership

php artisan route cache. Смотреть фото php artisan route cache. Смотреть картинку php artisan route cache. Картинка про php artisan route cache. Фото php artisan route cache

Laravel route caching for improved performance

Explore the idea of 100x faster route registration by using the route cache. How do your routes perform as your application grows?

The Laravel documentation explains that as long as you convert all your closure based routes to controller classes, you can leverage route caching. The documentation goes on to say:

Using the route cache will drastically decrease the amount of time it takes to register all of your application’s routes. In some cases, your route registration may even be up to 100x faster.

100x faster? Okay, you got my attention. How much time could route registration take anyway? It seems like it would be practically negligible, so why cache it?

In this article, we’ll review the principles behind Laravel routing, create our own routing experiments and discover when to utilize route caching to achieve speed-up.

Laravel Routing Primer

In config/app.php we see that App\Providers\RouteServiceProvider::class is listed as a default framework provider. App\Providers\RouteServiceProvider::class extends Illuminate\Foundation\Support\Providers\RouteServiceProvider which has its own boot function that looks like this:

(View the full file on github.)

Once the controller namespace is set, the boot method checks to see if the routes have been cached. Let’s explore what happens both with and without the route cache.

Without Route Cache

With Route Cache

Application requests will always load this cache file if it exists. The following is stated in the comment at the top of the file:

Here we will decode and unserialize the RouteCollection instance that holds all of the route information for an application. This allows us to instantaneously load the entire route map into the router.

Methodology

If routes are not cached, we immediately measure the time of loadRoutes(). Once the app is booted, we add the time it takes to run refreshNameLookups and refreshActionLookups. Lastly, we dump out the total captured time and kill the request.

If routes are cached, we measure the time it takes to call loadCachedRoutes(). However, notice that loadCachedRoutes() defers its work until the app is booted.

Let’s modify loadCachedRoutes to capture that time:

Tests

Let’s measure route registration time for an application with a single route. I have a new Laravel 5.6 install running through Homestead on my local development machine. Comment out all the routes in all the routes/ files. Then go into routes/web.php and add just one route like this:

Next add a TestController like so:

php artisan route cache. Смотреть фото php artisan route cache. Смотреть картинку php artisan route cache. Картинка про php artisan route cache. Фото php artisan route cache

Comment out dd() and visit /test in your browser to see how long the same route registration took using the route cache.

In this experiment, I ran each test 10 times (with and without cache) to get better statistical averages.

Scaling Up

Run the same experiment using 10, 100, 1,000 and 10,000 routes. routes/web.php looks something like this:

And the controller looks like this:

This allows us to see the effect of scaling the sheer number of routes in an application.

Other Considerations

How does passing in arguments via the routes affect route registration? We’ll run the experiment using parameters like this:

How does having multiple controllers affect route registration? We’ll use PHP to generate lots of new controllers like this. (You can run this in a route closure or in tinker.)

This spits out 1000 controllers named TestController000.php through TestController999.php that we can route to like so:

Results

The following are the average results for route registration given different # of routes.

No cache (ms)Cache (ms)Speed-up
1 route2.51.91.3x
105.22.62.0x
10022.54.35.3x
1,000166325.1x
10,0001,5133344.5x

By putting both the number of requests and the route registration duration on logarithmic scales we see an almost linear increase in route registration time as we add more routes to the application. This makes sense since Laravel loops through and processes each route entry one at a time.

php artisan route cache. Смотреть фото php artisan route cache. Смотреть картинку php artisan route cache. Картинка про php artisan route cache. Фото php artisan route cache

Speed-up is calculated by (old time) / (new time). Looking only at route registration speed-up resulting from route caching, we get the following (note that the # of routes is displayed on a logarithmic scale):

php artisan route cache. Смотреть фото php artisan route cache. Смотреть картинку php artisan route cache. Картинка про php artisan route cache. Фото php artisan route cache

These exact results are affected by the physical limitations of my development machine. However, we can still make some intelligent conclusions about route caching.

When we only had 10 routes, route caching would only shave 5.2 ms of route registration down to 2.6 ms. True, this is a speed-up of 2x, but it still only improves our total request lifecycle by 2.6 ms.

If our application has at least 100 routes, we start seeing speed-up around 5x. At this point we should definitely have route caching enabled. The route cache saves almost 20 ms per request and saves more as our application grows.

Variations

Here are the results for testing the effect of having route arguments and the effect of having a separate controller file for each route given an application with 1,000 routes.

No cache (ms)Cache (ms)Speed-up
Baseline166325.1x
5 arguments186414.5x
Separate controllers165295.7x

php artisan route cache. Смотреть фото php artisan route cache. Смотреть картинку php artisan route cache. Картинка про php artisan route cache. Фото php artisan route cache

Surprisingly, adding lots of arguments to routes only added around 10% extra time to our route registration without caching, though it added almost 30% when using caching. This is likely due to the larger quantity of information that the route cache is storing which needs to be loaded back into memory when the application runs.

Another interesting discovery is that using 1,000 controllers with one function each performed almost exactly the same in the route registration cycle as using one controller with all 1,000 functions, both cached and non-cached.

Wrap-Up

We certainly weren’t able to accomplish route registration 100x faster as mentioned in the Laravel documentation, but we achieved 5x which is significant enough to make a noticeable performance improvement in larger applications. Perhaps if we had registered routes in all 4 routes files we could have achieved higher total speed-up. Let me know if you discover a scenario where speed-up approaches 100x.

Be a FORCE FOR GOOD

VOLTAGE is a digital agency specializing in eCommerce, digital brand experiences, and web apps. Get emails and insights from our team:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *