Dynamic service imports in Symfony 2 allow for the flexible inclusion of services

I have defined parameters as follows:

parameters:
    config1:
        title: Title 1
        data_proc: getDataOne
        options: [things, stuff]
    config2:
        title: Title 2
        data_proc: getDataTwo
        options: [things, stuff]
#...

A service is set up as

my_service:
    class: Me\MyBundle\Services\MyService
    arguments:
        - @security.context
        - @doctrine.dbal.my_connection
        - %config% # the parameter that needs to be dynamic

controllers are coded in this way

class ProduitController extends Controller
{
    public function list1Action()
    {
        $ssrs = $this->get('my_service'); // with config1 parameters
        # ...
    }
    public function list2Action()
    {
        $ssrs = $this->get('my_service'); // using config2 parameters
        # ...
    }
    #...
}

Multiple controllers utilizing my_service.
In my list1Action(), I aim to access my_service by injecting only config1 parameters.

How can this be achieved without the need for defining a separate service for each controller?

Answer №1

Distinguish between two services that share the same class but have unique arguments, and choose one of them

Answer №2

If you create a public method in your Me\MyBundle\Services\MyService to set new parameters (such as setParameters($parameters)), you can easily use it in your controller like this:

class ProductController extends Controller
{
    public function showProducts()
    {
        $config = $this->container->getParameter('product_config');
        $service = $this->get('my_service')->setParameters($config);
    }

    public function listAllProducts()
    {
        $config = $this->container->getParameter('all_products_config');
        $service = $this->get('my_service')->setParameters($config);
    }
}

This approach provides an efficient solution.

While it is possible to override core classes for automatic parameter injection, consider if the time and effort required are truly justified.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrate PHP code within a JSON file

I am working on adding PHP code into a table (data), but I am not sure how to go about it. Can someone help me with this? This is my current code : $data['produit'] = ' <label for="designation" class="col-sm-1 control-l ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

Uploading large files on Vuejs causes the browser to crash

Whenever I try to upload a file using my browser (Chrome), everything goes smoothly for files with a size of 30mb. However, if I attempt to upload a file that is 150mb in size, the browser crashes. The server's maximum upload size has been configured ...

Having difficulty transferring serialized arrays from HTML to lower PHP files

I am attempting to transfer an array of checkbox inputs from an HTML page to an initial PHP file which creates a new layout for a page and then calls another PHP file to populate it. However, I am encountering issues with the serialization and unserializat ...

Drupal: Having difficulties with the "Send email" action to notify the commenter via email

After successfully setting up email notifications for new comments on my client's blog, I decided to also send a thank-you email to the comment poster. Using triggers and actions detailed here, I added [comment:author:mail] in the "Recipient" field as ...

Transferring a PHP session variable to JavaScript in a separate file

I successfully imported data from a CSV file into PHP and organized it into a nested array. To ensure the data is easily accessible across different files, I stored the array as a session variable. Now, the challenge lies in accessing this session variable ...

Understanding the response of AJAX in PHP

After exploring different ways for jQuery to interpret data in an AJAX call, I found that using JSON may be too complex for my needs. The PHP script I'm working with always returns a single integer string, sometimes followed by one or two additional ...

Using Zend 1 to display a different controller within a controller

My goal is to update the current layout to request the controller contents through AJAX instead of refreshing the page every time a user clicks on a menu item. To simplify, I want to load a controller from another controller. Let's assume we have a co ...

Create the shortest string possible that is not currently in the MySQL database

I'm currently working on creating a PHP script that can generate a unique short string not already existing in a MySQL database. If the generated string is already taken, I need the script to create a new one. This script will be used for my URL short ...

Suggestions for updating the 'begin' and 'finish' variables transmitted through ajax on fullcalendar?

Shown below is the URL to request JSON data via Ajax: '/php/get-events.php?start=2015-05-31&end=2015-06-07&_=1433154089490'. This query will fetch JSON data from 2015-05-31 to 2015-06-07. However, I am looking to retrieve data over a ...

PHP - Building URLs on the Fly

I have a link to a live video stream available. http://xxx.xxx.xxx.xxx:xxx/live/stream.m3u8 In order to enhance security and privacy, I am looking to create a dynamic link that constantly changes. To achieve this, some suggestions include generating a un ...

PHP File Permissions Issue When Generating Files

I have come across the following scenario: public_html - 755 => avatar - 777 => poll - 755 When I run the code provided below, I encounter an error (Warning: file_put_contents(../test.php) [function.file-put-contents]: failed to open ...

Codeigniter displays a view with an empty variable

After submitting data from another form, I am able to successfully retrieve and print the ID with `print($id)`. However, when I try to pass it to the view, the value returned is null. Below is the code snippet: Jquery post function viewAccount(orId) { ...

A PHP guide on iterating through statement results to populate an associative array

I am struggling to find the correct syntax to iterate through my results and populate them into an associative array. Currently, it only retrieves the first result and does not continue looping through the rest of the data. I have attempted various combina ...

Unable to modify the URL structure for an MVC project

I have been trying to find a solution by googling, but I am stuck here. Options +FollowSymLinks RewriteEngine On RewriteRule ^index\.php|style.css|img\.png$ - [L] # RewriteRule .* index.php [L] RewriteRule ^(.*)$ index.php?params=$1 [NC] ...

Preventing the execution of ajax code depending on the database query outcome

Within my bootbox dialog in a view named table_data.php, there is a "save" button. I am aiming to execute an Ajax post to the database based on the result obtained from a query in the home_model.php. I specifically want the data to be saved only if the da ...

PHP is not accurately calculating the upcoming birthday for users

I'm looking to create a birthday countdown timer that shows the time left until the next birthday. Birthdays occur once a year, typically within 365 days. I found this code snippet on stackoverflow to calculate the remaining time until the next birthd ...

Creating a JSON schema to organize regulations for internet inquiries

I am currently facing a challenge in structuring rules for web requests within a JSON object. Below are examples of the rules I need to store: Possible Conditions the user must be logged in the user must belong to an account of type [____] the user must ...

add to a visual representation of a chart in a separate database

Having an issue with yii2 and in need of assistance: I have two databases, db1 and db2, both on MsSQL. In db2, there is a view linked to a table in db1. The problem arises when I try to insert into db2 as I am unable to retrieve the transaction id using ...

A straightforward interval-based Ajax request

I've recently delved into the world of Ajax and jQuery. Just yesterday, I embarked on creating a simple ajax request for a form that sends a select list value to a PHP script and retrieves data from a database. Things are going smoothly so far! Howev ...