[NFR] Implement caching of assets in manager
I'd like to implement a caching method in generated assets, as i've done in this Manager, could it be done directly in C ?
<?php
namespace Frontvpg\Library\Assets;
use \Phalcon\Assets\Manager as PhManager;
use \Phalcon\Tag;
/**
* Add Asset caching
*
* @author Olivier Garbé <[email protected]>
*/
class Manager extends PhManager
{
/**
* Prints the HTML for JS resources
*
* @param string $collectionName the name of the collection
*
* @return string the result of the collection
**/
public function outputJs($collectionName = null)
{
$collection = $this->collection($collectionName);
if ($collection->getJoin()) {
$filename = $collection->getTargetPath();
if (file_exists($filename) && (filemtime($filename) > time())) {
return Tag::javascriptInclude($collection->getTargetUri());
}
$res = parent::outputJs($collectionName);
touch($filename, time() + 3500 + rand(50, 100));
return $res;
}
return parent::outputJs($collectionName);
}
/**
* Prints the HTML for CSS resources
*
* @param string $collectionName the name of the collection
*
* @return string the result of the collection
**/
public function outputCss($collectionName = null)
{
$collection = $this->collection($collectionName);
if ($collection->getJoin()) {
$filename = $collection->getTargetPath();
if (file_exists($filename) && (filemtime($filename) > time())) {
return Tag::stylesheetLink($collection->getTargetUri());
}
$res = parent::outputCss($collectionName);
touch($filename, time() + 3500 + rand(50, 100));
return $res;
}
return parent::outputCss($collectionName);
}
}
Regards
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
+1
+100
What about checking for if the files are modified?
Also, putting a unique timestamp on the link ensures there is no problems with client cache and CDNs.
Making this in the core would be much more elegant, but this does the job.
<?php
namespace Frontvpg\Library\Assets;
use \Phalcon\Assets\Manager as PhManager;
use \Phalcon\Tag;
/**
* Add Asset caching
*
* @author Olivier Garbé <[email protected]>
*/
class AssetsManager extends PhManager
{
/**
* Prints the HTML for JS resources
*
* @param string $collectionName the name of the collection
*
* @return string the result of the collection
**/
public function outputJs($collectionName = null)
{
$collection = $this->collection($collectionName);
if ($collection->getJoin()) {
$filename = $collection->getTargetPath();
if (file_exists($filename)) {
$time = 0;
foreach ($collection->getResources() as $resource) {
$tmp = filemtime($resource->getRealTargetPath());
if ($tmp > $time) {
$time = $tmp;
}
}
// If created
if (filemtime($filename) > $time) {
$collection->setTargetUri($collection->getTargetUri() . '?' . filemtime($filename));
return Tag::javascriptInclude($collection->getTargetUri());
}
}
// Else CREATE
$res = parent::outputJs($collectionName);
return $res;
}
return parent::outputJs($collectionName);
}
/**
* Prints the HTML for CSS resources
*
* @param string $collectionName the name of the collection
*
* @return string the result of the collection
**/
public function outputCss($collectionName = null)
{
$collection = $this->collection($collectionName);
if ($collection->getJoin()) {
$filename = $collection->getTargetPath();
if (file_exists($filename)) {
$time = 0;
foreach ($collection->getResources() as $resource) {
$tmp = filemtime($resource->getRealTargetPath());
if ($tmp > $time) {
$time = $tmp;
}
}
// If created
if (filemtime($filename) > $time) {
$collection->setTargetUri($collection->getTargetUri() . '?' . filemtime($filename));
return Tag::stylesheetLink($collection->getTargetUri());
}
}
// Else CREATE
$res = parent::outputCss($collectionName);
return $res;
}
return parent::outputCss($collectionName);
}
}
duplicate ticket: #925
@ogarbe, @atduarte
imo it would be better to check only the concated / minified file by using a general join cache method.
the question is how often do you modify asset files like this in production mode?
why should we check each request whether a collection file like js/css
should be or not should be minified / concated if we are in production mode?
usually you have a deployment process where you perform some stuff like
php bin/console cache:clean or php bin/console cache:warmup etc.
idea:
...
$asset->setJoinCache('7 days'); // create timestamp
...
if (filemtime($filename) > $joinCacheTime) {
// do concate / minify file
}
// display concated / minified file
what do you think?
In my env, js cached assets can contains translation information, so having one hour caching is good, as translation can be done quite often.
Your idea of setJoinCache is the good implementation, in my case it'll be '1h' :smile:
+1. Today I realized that this feature is very useful.
+1
+1
+1
+1
Adding check for external files, I use several CDN and I needed to add some lines.
<?php
namespace Frontvpg\Library\Assets;
use \Phalcon\Assets\Manager as PhManager;
use \Phalcon\Tag;
/**
* Add Asset caching
*
* @author Olivier Garbé <[email protected]>
*/
class AssetsManager extends PhManager
{
/**
* Prints the HTML for JS resources
*
* @param string $collectionName the name of the collection
*
* @return string the result of the collection
**/
public function outputJs($collectionName = null)
{
$collection = $this->collection($collectionName);
if ($collection->getJoin()) {
$filename = $collection->getTargetPath();
if (file_exists($filename)) {
$time = 0;
foreach ($collection->getResources() as $resource) {
if ($resource->getLocal()) {
$tmp = filemtime($resource->getRealTargetPath());
if ($tmp > $time) {
$time = $tmp;
}
}
}
// If created
if (filemtime($filename) > $time) {
$collection->setTargetUri($collection->getTargetUri() . '?' . filemtime($filename));
return Tag::javascriptInclude($collection->getTargetUri());
}
}
// Else CREATE
$res = parent::outputJs($collectionName);
return $res;
}
return parent::outputJs($collectionName);
}
/**
* Prints the HTML for CSS resources
*
* @param string $collectionName the name of the collection
*
* @return string the result of the collection
**/
public function outputCss($collectionName = null)
{
$collection = $this->collection($collectionName);
if ($collection->getJoin()) {
$filename = $collection->getTargetPath();
if (file_exists($filename)) {
$time = 0;
foreach ($collection->getResources() as $resource) {
if ($resource->getLocal()) {
$tmp = filemtime($resource->getRealTargetPath());
if ($tmp > $time) {
$time = $tmp;
}
}
}
// If created
if (filemtime($filename) > $time) {
$collection->setTargetUri($collection->getTargetUri() . '?' . filemtime($filename));
return Tag::stylesheetLink($collection->getTargetUri());
}
}
// Else CREATE
$res = parent::outputCss($collectionName);
return $res;
}
return parent::outputCss($collectionName);
}
}
There are many ways to optimize the processing resources. I'll describe a simple method below which allows to handle resourses directly through web server to optimize the response time.
First we need to set up the Assets Manager. We'll use base controller, but you can use the service provider or any other place:
<?php
namespace App\Controllers;
use Phalcon\Mvc\Controller;
use Phalcon\Assets\Filters\Jsmin;
/**
* App\Controllers\ControllerBase
*
* This is the base controller for all controllers in the application.
*/
class ControllerBase extends Controller
{
public function onConstruct()
{
$this->assets
->useImplicitOutput(false)
->collection('global')
->addJs('https://code.jquery.com/jquery-3.2.1.js', false, true)
->addFilter(new Jsmin());
}
}
Then we have to configure the routing:
<?php
/*
* Define custom routes.
* This file gets included in the router service definition.
*/
$router = new Phalcon\Mvc\Router();
$router->addGet('/assets/(css|js)/([\w.-]+)\.(css|js)', [
'controller' => 'assets',
'action' => 'serve',
'type' => 1,
'collection' => 2,
'extension' => 3,
]);
// Other routes...
Finally, we need to create a controller to handle resource requests:
<?php
namespace App\Controllers;
use Phalcon\Http\Response;
/**
* Serve site assets.
*/
class AssetsController extends ControllerBase
{
public function serveAction() : Response
{
// Getting a response instance
$response = new Response();
// Prepare output path
$collectionName = $this->dispatcher->getParam('collection');
$extension = $this->dispatcher->getParam('extension');
$type = $this->dispatcher->getParam('type');
$targetPath = "assets/{$type}/{$collectionName}.{$extension}";
// Setting up the content type
$contentType = $type == 'js' ? 'application/javascript' : 'text/css';
$response->setContentType($contentType, 'UTF-8');
// Check collection existence
if (!$this->assets->exists($collectionName)) {
return $response->setStatusCode(404, 'Not Found');
}
// Setting up the Assets Collection
$collection = $this->assets
->collection($collectionName)
->setTargetUri($targetPath)
->setTargetPath($targetPath);
// Store content to the disk and return fully qualified file path
$contentPath = $this->assets->output($collection, function (array $parameters) {
return BASE_PATH . '/public/' . $parameters[0];
}, $type);
// Set the content of the response
$response->setContent(file_get_contents($contentPath));
// Return the response
return $response;
}
}
If precompiled resources exist in the file system they must be served directly by web server. So to get the benefit of static resources we have to update our server configuration. We will use an example configuration for Nginx. For Apache it will be a little different:
location ~ ^/assets/ {
expires 1y;
add_header Cache-Control public;
add_header ETag "";
# If the file exists as a static file serve it directly without
# running all the other rewrite tests on it
try_files $uri $uri/ @phalcon;
}
location / {
try_files $uri $uri/ @phalcon;
}
location @phalcon {
rewrite ^(.*)$ /index.php?_url=$1;
}
# Other configuration
We need to create assets/js and assets/css directories in the document root of the application (eg. public).
Every time when the user requests resources using address of type /assets/js/global.js the request will be redirected to AssetsController in case this file is absent in the filesystem. Otherwise the resource will be handled by the web server.
It isn't the best example. However, it reflects the main idea: the reasonable configuration of a web server with an application can help optimize response time multifold.
As you can see we don't need to override Phalcon's internal classes.
Thank you for contributing to this issue. As it has been 90 days since the last activity, we are automatically closing the issue. This is often because the request was already solved in some way and it just wasn't updated or it's no longer applicable. If that's not the case, please feel free to either reopen this issue or open a new one. We will be more than happy to look at it again! You can read more here: https://blog.phalconphp.com/post/github-closing-old-issues