“To err is human, to purr is feline.” – R. Byrne
– You are wrong!
My eyes are bleeding, world is crushing my brain. Why so early?
– You are wrong, about the assets…!
What assets? What.. ah.. assets, composer, module, scripts. Now I remember.
But let’s start from beginning.
As you maybe remember I wrote a little article about deploying Magento’s assets that serves for some internal processes. If you missed that please, check my Composer: scripts entry.
To make it short, I used composer hook to deploy some assets to pub/media. It is a good idea to separate deployment from data setup. Then why I was wrong?
Paweł Tatarczuk asked me why I do not want to put those assets in frontend/web… and… that’s a good question. I missed the obvious? Maybe I did, but before I will answer this question let me first show you the new solution.
Again, what is the situation? We have a module with “copy files into magento root” installation instruction. In module there are assets in pub directory that serves for some process connected with google map markers. Those assets must be accessible by http protocol. That is why developers of the module put those assets in pub/media and tell us to copy them into root.
That’s a fundamentally wrong approach.
Paweł’s solution was simple. Put images in view/frontend/web, run php bin/magento setup:static-content:deploy and voila, any external app can request for them.
This solution is better than mine… under some circumstances.
In module there is a helper that, among the others, generates image’s url
public function getMediaUrlImage($imagePath = '')
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $imagePath;
Besides of the fact that this method breaks the Law of Demeter, more important is that it uses images from media.
Instead, we could adjust this helper to serve assets from statics by using the following method:
Magento\Framework\View\Asset::getUrlWithParams($fieldId, array $params)
That is all true. This solution is better. Those assets should not be put in pub/media in the first place. And, of course, module should be a composer’s package.
Other hidden assumption behind this solution is that I actually want to modify the module’s code.
But I don’t. Changing the module’s force me to maintain it forever. Also, for some reasons I could not simply override the helper.
My task was clear – make it a composer’s module without changing it.
Even though Pawel’s solution was great if I could modify or add some code, it would not work for me.
Nevertheless, I thinks it is a way to go for any model that I will create in the future. I will put assets in web directory and deploy them with static-content deploy functionality. Great!
Since then I found many more modules which use the same approach – put files in module/pub, copy them manually to pub/media. Facing this issue so often I am sure that presented solution will open someone’s eyes.
Thanks Paweł 🙂
See you next time!