Задать вопрос
  • PHP. Несколько вариантов в switch case. Какие есть решения?

    GHua
    @GHua
    abstract class AbsctactFileProcessor
    {
        abstract public function supports($extension);
        abstract public function process($file);
    }
    
    class ProcessingProvider
    {
        
        private $processors;
    
        public function __construct()
        {
            $this->processors = array();
        }
    
        public function addProcessor(AbsctactFileProcessor $processor)
        {
            $this->processors[] = $processor;
    
            return $this;
        }
    
        public function process($file)
        {
            $file = new \SplFileInfo($file);
            $extension = $file->getExtension();
            foreach ($this->processors as $processor) {
                if ($processor->supports($extension)) {
    
                    return $processor->process($file);
                }
            }
    
            throw new \LogicException();
        }
    
    }
    
    class SimpleTextProcessor extends AbsctactFileProcessor
    {
    
        public function process($file)
        {
            // return ...
        }
    
        public function supports($extension)
        {
            return in_array($extension, array('txt'));
        }
    
    }
    
    class ImageProcessor extends AbsctactFileProcessor
    {
    
        public function process($file)
        {
            // return ...
        }
    
        public function supports($extension)
        {
            return in_array($extension, array('png', 'gif', 'bmp', 'jpg'));
        }
    }
    
    $provider = new ProcessingProvider();
    $provider->addProcessor(new \SimpleTextProcessor());
    $provider->addProcessor(new \ImageProcessor());
    
    $provider->process('mybestfile.exe');
    Ответ написан
    2 комментария