Symfony 4中是否存在可创建带方法控制器的命令?
Hey there! I get where you're coming from—switching from Laravel's artisan to Symfony's console commands can feel a bit disorienting at first. Let's fix this controller generation issue for you.
The Short Answer (What You Need Right Now)
Symfony 4 uses the MakerBundle for generating boilerplate code, replacing the old generate: commands you tried. To create a controller with pre-defined methods, required use statements, and even basic routing, run this command:
php bin/console make:controller PhotoController
What This Does for You
When you run that command, Symfony will:
- Create a new controller file at
src/Controller/PhotoController.php - Automatically include the necessary
usestatements you mentioned:use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Response; - Generate a default
index()method with a pre-configured route, like this:/** * @Route("/photo", name="photo") */ public function index(): Response { return new Response('Hello World!'); } - You can immediately start adding more methods to this controller, and if you need to generate additional routes later, you can use
make:routeto scaffold those too.
Why Your Old Commands Failed
Let's quickly clear up why those earlier attempts didn't work:
php app/console ...: Symfony 4 moved the console script fromapp/consoletobin/console—that's why you got the "Could not open input file" error.php bin/console generate:controller: The oldgenerate:namespace commands belonged to theSensioGeneratorBundle, which isn't installed by default in Symfony 4+. The official replacement is the MakerBundle, which is designed to be more intuitive and aligned with modern Symfony practices.
If MakerBundle Isn't Installed (Rare for New Symfony 4 Projects)
If for some reason you don't have the MakerBundle (it's included in Symfony 4's standard skeleton), install it via Composer:
composer require maker --dev
That should cover everything you need to get up and running with controller generation in Symfony 4, no manual use statements required!
内容的提问来源于stack exchange,提问作者Angel

