PHP中的数据库和OOP实践 [英] Database and OOP Practices in PHP

查看:105
本文介绍了PHP中的数据库和OOP实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它很难解释这种情况,但请看示例。

Its difficult to explain this situation but please see the example.

我已经编码了一个网站加载页面,我初始化一个数据库类。我将这个类作为函数参数发送到需要访问数据库的任何函数。

I have coded a website where the page loads, I initialize a database class. I sent this class as a function parameter to any functions that needs to access database.

我知道这是不好的方法,但目前我没有线索如何做这个任何其他方式。

I know this is bad approach but currently I have no clue how to do this any other way. Can you please help me.

示例

class sms {

    function log_sms($message, $db) {

        $sql = "INSERT INTO `smslog` SET
            `mesasge` = '$message'
            ";
        $db->query($sql);

        if ($db->result)
            return true;
        return false;
    }

}

$db = new db(username,pass,localhost,dbname);

$sms = new sms;

$sms->log_sms($message, $db);

有没有比这更好的方法?

Is there any better approach than this ?

推荐答案

有多个选项如何解决依赖性问题(对象A需要对象B):

there are number of options how to resolve dependencies problem (object A requires object B):

构造函数注入

  class Sms { 
        function __construct($db) ....
  }

  $sms = new Sms (new MyDbClass);

setter注入

  class Sms { 
        protected $db;
  }
  $sms = new Sms;
  $sms->db = new MyDbClass;

'registry'模式

'registry' pattern

 class Registry {
     static function get_db() {
          return new MyDbClass;
 }}

 class Sms {
      function doSomething() {
          $db = Registry::get_db();
          $db->....
  }}

定位器模式

 class Loader {
     function get_db() {
          return new MyDbClass;
 }}

 class Sms {
      function __construct($loader) {
         $this->loader = $loader;

      function doSomething() {
          $db = $this->loader->get_db();
          $db->....
  }}

  $sms = new Sms(new Loader);

基于自动化容器的依赖注入,参见例如 http://www.sitepoint.com/blogs/2009 / 05/11 / bucket-is-a-minimal-dependency-injection-container-for-php

automated container-based dependency injection, see for example http://www.sitepoint.com/blogs/2009/05/11/bucket-is-a-minimal-dependency-injection-container-for-php

   interface DataSource {...}
   class MyDb implements DataSource {...}

    class Sms {
        function __construct(DataSource $ds) ....


    $di = new Dependecy_Container;
    $di->register('DataSource', 'MyDb');
    $sms = $di->get('Sms');      

命名为)

也是Fowler的文章我给你以前真的值得阅读

also the Fowler's article i gave you before is really worth reading

这篇关于PHP中的数据库和OOP实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆