Search code examples
phpsymfonyservicevichuploaderbundle

How to implement services that relate to third party bundles?


There is one thing that I dont want to miss about Symfony, because I thought I could not understood so good. Could you help me?? I'll put the bundle VichUploaderBundle as example, but in others the same is happened.

The documentation says how to create a custom directory, but in my case I would like to relate to id from news. Example directory: upload/news/:news_id/image.jpg

What I understand with this is that i have to create two diferent services, one for upload_destination and other for directory_namer, I´m right?

config.yml

vich_uploader: 
    # ... 
    mappings: 
    product_image: 
    upload_destination: news_image 
    directory_namer:    my.directory_namer.news  

But how I can do it? If I follow the documentation from Symfony, I should create this way the Synfony services.

What steps should I follow? I think create a class in my Newsbundle and assign it as ´services`. Its ok?

How I could do a capture in the class that i have been created as service the news_id? and the fine image_name to save it in the database? and then save the custom directory also?

This is for me a very important thing to learn, because I think knowing this helps me understand the others bundles and how to aplicate them.

In summary:

How do I save to a custom directory with the id of the news and how rename the image with the id of the news?

I hope you can help me.

thanks, Carlos.


Solution

  • The ways to interact with an external bundle are multiple :

    • Use Events triggered by the bundle
    • Configuration override
    • Declare services which will be manipulated by the bundle (like in your example)
    • Override the bundle - some bundles put some classes path into their configuration, you can use your own classe by override this.

    I never used VichUploaderBundle, but after a quick look into his documentation, it seems that your service named "my.directory_namer.news" should implement the DirectoryNamerInterface (https://github.com/dustin10/VichUploaderBundle/blob/master/Naming/DirectoryNamerInterface.php)

    Then, you can define the "directoryName" method imposed by the interface and put your logic into it to build the directory's name from the object (the news).

    Hope this will help you.

    Best regards, J