简体   繁体   中英

Symfony 2 asset, check if file exists performance

on symfony 2, using Twig you can use the asset() function to link an image in the way
{{ asset('path_to_the_image') }} , now if the file does not exists then the src of the file keeps the same,

Thinking about that, I was tempted to create another Twig function on my TwigExtensions , in order to check the file existence, in order to do the following, If the file exists then I will use the given url and if does not exists then I will change the result of the function to a default image that I will use as a not_image image. The motivation for this function is to always show an image to the user.

Now, my question.

I can't figure out the performance issues with this approach because I will check the file twice, the first time to check if exists and the other time is the request that asks for the file. And the usual thing to do is to put the asset address and in case the file does not exists replace it with some default file using javascript.

I will use php's file_exists function, and on the manual I have read that is very inexpensive and that in case that the file indeed exists the result is cached to avoid performance issues.

Thanks in advance...

file_exists triggers a read access to your file system (or, even just the FS metadata). This is very inexpensive indeed. Keep in mind that, when running a Symfony application, you're usually accessing hundreds of PHP files alone.

The result of file_exists is cached indeed, but only while during the execution of a script. So, if you call file_exists several times within one script execution (and don't call clearstatcache in between), the result is cached. If you call the script again later, PHP will look for the file again.


However, if you really worry about performance, you shouldn't check for the files' existence “on the fly”, but instead create a Symfony command that checks if all linked assets are valid during building or deployment.

This command would basically render all pages, and your custom asset function would, instead of returning a dummy image, throw an exception. This way, you only need to check once, during deployment, if all assets are valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM