【问题标题】:Php switch to interfacephp切换到界面
【发布时间】:2021-05-08 02:23:53
【问题描述】:

有没有办法用多态(接口)替换这个开关盒? 我得到了一个具有不同字段的表单,具体取决于产品类型,它将数据传递到数据库中。

public function typeHandler(){ 
switch($this->type){
  case 'unknown':
    return '';
  case 'dvd':
    $dvd = new Dvd($_POST);
    $product = new Product($_POST);
    $sa = $dvd->getSize();
    $product->setSa($sa);
    $product->save();
    $dvd->save();
    break;
  case 'book':
    $book = new Book($_POST);
    $product = new Product($_POST);
    $sa = $book->getWeight();
    $product->setSa($sa);
    $product->save();
    $book->save();
    break;
  case 'furniture':
    $furniture = new Furniture($_POST);
    $product = new Product($_POST);
    $sa = $furniture->getDimensions();
    $product->setSa($sa);
    $product->save();
    $furniture->save();
    break;
}

}

【问题讨论】:

    标签: php forms interface switch-statement polymorphism


    【解决方案1】:

    您可以执行以下操作(一种方法):

    
    interface Item {
       // This method will replace Dvd::getSize(), Book::getWeight() and Furniture::getDimensions().
       public function getSa();
       public function save();
    }
    
    class Dvd implements Item {
       ...
    }
    
    class Book implements Item {
       ...
    }
    
    class Furniture implements Item {
       ...
    }
    
    class ItemFactory {
        private $types = [
            'dvd' => Dvd::class,
            'book' => Book::class,
            'furniture' => Furniture::class,
        ];
    
        public function create($type, $constructData) {
            if (array_key_exists($type, $this->types)) {
                return new $this->types[$type]($constructData);
            }
            throw new Exception('No such type!');
        }
    }
    
    ...
    
    public function typeHandler() { 
        $item = (new ItemFactory)->create($this->type, $_POST);
        $product = new Product($_POST);
        $product->setSa($item->getSa());
        $product->save();
        $item->save();
    }
    

    注意:不知道为什么单独的Product 类可以与Item 接口完全合并,具体取决于细节。

    【讨论】:

    • 谢谢Zoli :)
    • @Remy 感谢您纠正错字。
    猜你喜欢
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多