问题
For quite a while I've been trying to understand how to add my own library of functions that I want to use in my Web-App's different controller/bundles, but I just found that I needed to 'house' these functions a Symfony Service Container.
Unlike other computer languages, Services, are not a background process!
To get a better handle on this, I tried out the example in the Symfony v2.8 guide section on Creating/Configuring Services in the Container. I created the following file in the suggested directory:
<?php // <=== This was missing from the MessageGenerator.php file!
//
// Adding it to the file solved the autoloader error, and now the MessageGenerator
// class loads properly!
//
// src/AppBundle/Service/MessageGenerator.php
namespace AppBundle\Service;
class MessageGenerator {
public function getHappyMessage() {
$messages = [
'You did it! You updated the system! Amazing!',
'That was one of the coolest updates I\'ve seen all day!',
'Great work! Keep going!'
];
$index = array_rand($messages);
return $messages[$index];
}
}
Then I added the following to the services configuration file:
# app/config/services.yml
services:
app.message_generator:
class: AppBundle\Service\MessageGenerator
arguments: []
And then I placed the following lines in a controller/bundle that otherwise was previously working:
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
When I uploaded these files and ran the associated web-page, I got:
The autoloader expected class "AppBundle\Service\MessageGenerator" to be defined in
file "/var/www/vhosts/symfony2/vendor/composer/../../src/AppBundle/Service/
MessageGenerator.php". The file was found but the class was not in it, the class name
or namespace probably has a typo.
This message appears to be saying that the MessageGenerator.php file was found in the src/AppBundle/Service directory. However the class MessageGenerator was not defined in the MessageGenerator.php file because the file wasn't recognised as a php file due to the missing
回答1:
The MessageGenerator.php file was missing
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
lines were executed, and $generatedMessage contained one of the array element messages, as expected.
来源:https://stackoverflow.com/questions/57918637/how-to-fix-symfony-v2-8-creating-configuring-services-in-the-container-autolo