0

我有这节课

class Controller {

    protected $f3;
    protected $db;


    function __construct()
    {

        $f3=Base::instance();

    $db=new \DB\SQL('mysql:host=62.xxx;port=3306;dbname=Sqlxxx','xxxx','xxxxx');

    $this->f3=$f3;
    $this->db=$db;

    $this->db->exec('SET CHARACTER SET utf8');
    $this->db->exec('SET time_zone = \'+00:00\'');

    }
}

和他的孩子

class WebController extends Controller {
    public function login()
    {
        $db=new \DB\SQL('mysql:host=62.xxx;port=3306;dbname=Sqlxxx','xxxx','xxxxx');
        $user = new \DB\SQL\Mapper($db, 'users');
        $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password'));
    }
 }

我需要$dbWebController 中的另一个对象,您可以注意到,目前我确实重复了代码。

我如何在没有重复代码的情况下从父级调用 $db?我确实尝试过

$db = parent::__construct();

没有运气。谢谢

4

2 回答 2

1

You should extract creaing $db to method (createConnection) ie.:

class Controller {
    protected $f3;
    protected $db;


    function __construct()
    {
        $this->f3=Base::instance();
        $this->db=$this->createConnection();  
    }
    protected function createConnection() {
        $db = new \DB\SQL('mysql:host=62.xxx;port=3306;dbname=Sqlxxx','xxxx','xxxxx');
        $db->exec('SET CHARACTER SET utf8');
        $db->exec('SET time_zone = \'+00:00\'');
        return $db;
    }
}

And then you can use extracted method:

class WebController extends Controller {
    public function login()
    {
        $db=$this->createConnection();
        $user = new \DB\SQL\Mapper($db, 'users');
        $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password'));
    }
}

Or use connection created via constructor

class WebController extends Controller {
    public function login()
    {
        $user = new \DB\SQL\Mapper($this->db, 'users');
        $auth = new \Auth($user, array('id'=>'username', 'pw'=>'password'));
    }
}
于 2013-11-03T18:36:28.057 回答
1

作为良好实践,您应该明确地将您的构造函数声明为公共的。

您没有覆盖子构造函数,因此使用父构造函数。

子继承受保护的父属性。

因此,您可以使用 $this->db 访问父级的数据库对象。

于 2013-11-03T19:15:57.743 回答