【问题标题】:oop structure for make class such as PDO class structuremake 类的 oop 结构,例如 PDO 类结构
【发布时间】:2015-06-22 07:50:42
【问题描述】:

如何制作类似 PDO 或 ORM 的类结构

 $query = DB::table('users')->select('name');

 $users = $query->addSelect('age')->get();

 $stmt = $pdo->prepare($sql);
 $stmt->bindvalue(':u',intval($_SESSION['userId']),PDO::PARAM_INT);
 $stmt->execute();

$query 或 $stmt 返回什么?

如何设计像他们一样的类结构?

谢谢

编辑

 $query = DB::table('users')->select('name');
 meaning : 
 function select(){
  //
  return $this;
 }

为此结构返回到 $query 的内容:

 $query->addSelect('age')->get();

【问题讨论】:

    标签: php oop design-patterns pdo orm


    【解决方案1】:

    PDO 是通过返回一个带有自己的方法 (read more about it) 的新类 (PDOStatement) 来完成的,但它与以下内容相同:

    <?php
    class ClassOne
    {
        private $connection;
        public function __construct($database_stuff)
        {
            $this->connection = $database_stuff;
        }
    
        public function prepare($sql)
        {
            // Code that does something with the $sql
            // Then return a new class
            return new ClassTwo($this);
        }
    }
    
    class ClassTwo
    {
        private $ClassOne;
    
        public function __construct(ClassOne $Class)
        {
            $this->ClassOne = $Class;
        }
    
        public function execute()
        {
            // Code that does something with ClassOne
        }
    }
    
    # Start that initial class
    $Class = new ClassOne('database:type;host=example;etc=yadayada');
    # Do class one method
    $query = $Class->prepare("SELECT * FROM fake_table");
    # $query is now ClassTwo, so you do method from ClassTwo
    $query->execute();
    

    之所以能够将方法链接在一起,是因为当前方法以$this的形式返回对象:

    <?php
        class   DBClass
        {
            protected   $connection,
                        $value;
    
            public  function __construct($connection)
            {
                $this->connection   =   $connection;
            }
    
            public  function prepare($value)
            {
                $this->value    =   $value;
                # Return the object
                return $this;
            }
    
            public  function execute()
            {
                echo $this->value;
                # Return the object
                return $this;
            }
        }
    
        $con    =   new DBClass("login creds");
        $con->prepare("update stuff if stuff = 'things'")->execute();
    ?>
    

    【讨论】:

    • 谢谢,可以使用__call在这个类中添加闭包方法吗??!
    猜你喜欢
    • 2012-07-26
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多