2013-10-11 8 views
7

मैं सिम्फनी के लिए नया हूं। मैंने एक कस्टम कमांड बनाया है जिसका एकमात्र उद्देश्य सिस्टम से डेमो डेटा मिटा देना है, लेकिन मुझे नहीं पता कि यह कैसे करें।Symfony2 - कस्टम कंसोल कमांड में सेवा का उपयोग कैसे करें?

नियंत्रक में मैं करना होगा:

$nodes = $this->getDoctrine() 
    ->getRepository('MyFreelancerPortfolioBundle:TreeNode') 
    ->findAll(); 

$em = $this->getDoctrine()->getManager(); 
foreach($nodes as $node) 
{ 
    $em->remove($node); 
} 
$em->flush(); 

आदेश में निष्पादित() फ़ंक्शन से ऐसा करने से मुझे मिलता है:

Call to undefined method ..... ::getDoctrine(); 

मैं निष्पादित() फ़ंक्शन से करना होगा कैसे ? साथ ही, यदि उनके माध्यम से लूप के अलावा डेटा को पोंछने और उन्हें हटाने का कोई आसान तरीका है, तो इसका उल्लेख करने में संकोच न करें।

उत्तर

11

सेवा कंटेनर तक पहुंचने में सक्षम होने के लिए आपके आदेश को Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand का विस्तार करने की आवश्यकता है।

कमांड प्रलेखन अध्याय - Getting Services from the Container देखें।

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; 
// ... other use statements 

class MyCommand extends ContainerAwareCommand 
{ 
    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $em = $this->getContainer()->get('doctrine')->getEntityManager(); 
     // ... 
6

Symfony 3.3 (मई 2017) के बाद से आप आसानी से आदेशों में निर्भरता इंजेक्शन का उपयोग कर सकते हैं।

बस अपने services.yml में PSR-4 services autodiscovery का उपयोग करें:

services: 
    _defaults: 
     autowire: true 

    App\Command\: 
     resource: ../Command 

तो आम निर्माता इंजेक्शन और अंत का उपयोग भी Commands साफ वास्तुकला होगा:

final class MyCommand extends Command 
{ 
    /** 
    * @var SomeDependency 
    */ 
    private $someDependency; 

    public function __construct(SomeDependency $someDependency) 
    { 
     $this->someDependency = $someDependency; 

     // this is required due to parent constructor, which sets up name 
     parent::__construct(); 
    } 
} 

यह (या पहले से ही किया जाएगा, के निर्भर करता है समय पढ़ने) मानकों के बाद सिम्फनी 3.4 (नवंबर 2017), जब commands will be lazy loaded

संबंधित मुद्दे