Reputation: 164
How to call symfony service in custom php file? Service already created in bundle. This php script will run from command line. Please help.
Upvotes: 1
Views: 199
Reputation: 1648
Create a custom php file as you described is not a good practice, typically services are called from a Controller.
If you need to run some code from the command line, you can use the Symfony Console Commands, that allows you to execute asynchronous tasks with Crons, for example.
As described in Symfony docs, you can pass as many service that you need passing it to the command constructor, here you can find a basic example:
use Symfony\Component\Console\Command\Command;
use App\Service\UserManager;
class CreateUserCommand extends Command
{
private $userManager;
public function __construct(UserManager $userManager)
{
$this->userManager = $userManager;
parent::__construct();
}
// ...
protected function execute(InputInterface $input, OutputInterface $output)
{
// ...
$this->userManager->create($input->getArgument('username'));
$output->writeln('User successfully generated!');
}
}
Please, take a look into this link: https://symfony.com/doc/current/console.html#getting-services-from-the-service-container
Hope this help!
Upvotes: 2