Home >Backend Development >PHP Tutorial >Share a useful Cache macro in Laravel_PHP tutorial
The caching tool provided by Laravel is very useful. The manual introduces some basic usage, such as get, put, forget, forever, etc. , at first I used it like this:
The code is as follows:
This is the most basic usage. It automatically determines whether the cache exists. If it does not exist, it will be fetched from the database and written to the cache.
Later I discovered that the model also comes with the remember and rememberForever methods. For example, it can be like this:
The code is as follows:
This has limitations. It cannot completely cache data during complex queries. For example, when using with() to preload related data, related data cannot be cached.
Then I discovered that Cache can also customize macro methods like Response, so I tried the following:
The code is as follows:
This method can be placed in bootstrap/start.php, or it can be placed in App::before() in filter. It is convenient for your own project. Let’s see how to use it:
The code is as follows:
I personally like this way of writing. I hope you all like the content of this article.