在 PHP 中实现相同的方法重载行为的最佳方法是什么?

假设我有两个名为Userand的类Product。这两个都需要保存在数据库中。


第三个类称为PersistencyHandler处理所有数据库交互(为了遵守单一责任原则和依赖倒置)。这是这个类的样子:


<?php

/**

 * Class PersistencyHandler

 * Handles database using PDO API

 */

class PersistencyHandler{


    /**

     * PDO connection used to save objects into.

     * @var $conn PDO

     */

    private $conn;


    /**

     * PDODatabaseSaver constructor.

     * @param $conn PDO

     */

    public function __construct($conn){

        $this->pdo = $conn;

    }


    /**

     * Saves the given object in the database

     * @param $object mixed

     */

    public function save($object){


        // as PHP does not support classic method overloading for different

        // types of objects, this is the cleanest solution I've been able to find.

        // And it's still pretty dirty...


        if($object instanceof Product) {

            $this->saveProduct($object);

        } else if($object instanceof User) {

            $this->saveUser($object);

        } else {

            throw new UnsupportedOperationException("Cannot save object, unsupported type."); // custom class

        }

    }



    private function saveProduct(Product $object){

        // save Product into database

    }


    private function saveUser(User $object){

        // save User into database

    }


}

?>

我来自 Java 经验,我确信使用instanceof是一种非常糟糕的做法(至少在 Java 中)。例如,在 Java 中,我曾经使用重载方法来解决此类问题。


我检查了php.net和其他网站(包括这个网站),但我没有找到一个很好的答案来回答我的问题:


以正确的方式实现上述代码的相同行为的更好方法是什么?


请注意,我有一个带有单个参数的方法,调用的方法由参数的类型决定。


函数式编程
浏览 77回答 1
1回答

蓝山帝景

一种解决方案是使用动态调用(类似于 Java 中的反射):public function save($object){&nbsp; &nbsp; $mtd = 'save'.get_class($object);&nbsp; &nbsp; if(method_exists($this, $mtd))&nbsp; &nbsp; &nbsp; &nbsp; call_user_func(array($this, $mtd), $object);&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; throw new UnsupportedOperationException("Cannot save object, unsupported type.");}注意:如果您使用命名空间,则需要修改代码(get_class() 返回限定名称)。
打开App,查看更多内容
随时随地看视频慕课网APP