依赖注入在PHP [英] Dependency Injection in PHP

查看:186
本文介绍了依赖注入在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找到依赖注入。

  • 我是上的东西或者是完全关闭?
  • 是code好坏 - 依赖注入与否

下面code是一个CMS系统

基础

现在有一个叫做page_details与所有存储在其中的网页表格。

目录/文件结构

 的.htaccess
的index.php
类/ Db.class.php
类/ Page.class.php
配置/ config.php文件
配置/的init.php
 

的.htaccess

 #mod-rewrite启用。
选项​​+的FollowSymLinks
RewriteEngine叙述上

#----规则----

重写规则^([A-ZA-Z0-9 -_] +)\。HTML $的index.php?网页= $ 1 [NC,L]
 

的index.php

 < PHP的require_once('配置/的init.php'); ?>
!< D​​OCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtmlXML:LANG =ENLANG =EN>
< HEAD>
    < META HTTP-当量=内容类型内容=text / html的;字符集= ISO-8859-1/>
    < META HTTP-当量=imagetoolbarCONTENT =NO/>
    <冠军>< /标题>
    < META NAME =说明内容=/>
    < META NAME =关键词内容=/>
    <链接HREF =/ CSS / Styles.css中媒体=屏幕相对=样式类型=文本/ CSS/>
< /头>
<身体GT;
< PHP
$页=新的页面($分贝);
的print_r($页级> get_page($ _ GET ['页']));
?>
< /身体GT;
< / HTML>
 

Db.class.php

 < PHP
一流的分贝
{
    私人$ DBHOST;
    私人$ DBUSER;
    私人$ DBPASSWORD;
    私人$ DBNAME;
    私人$连接;
    公众$查询;
    功能__construct($ DBHOST,$ DBUSER,$ DBPASSWORD,$ DBNAME)
    {
        $这个 - > DBHOST = $ DBHOST;
        $这个 - > DBUSER = $ DBUSER;
        $这个 - > DBPASSWORD = $ DBPASSWORD;
        $这个 - >数据库名= $ DBNAME;
    }
    公共职能OPEN_CONNECTION()
    {
        尝试
        {
            $这个 - >连接= mysqli_connect($这个 - > DBHOST,$这个 - > DBUSER,$这个 - >
                DBPASSWORD,$这个 - > DBNAME);
        }
        赶上(异常$ E)
        {
            抛出$ê;
        }
    }
    公共职能密切($查询)
    {
        尝试
        {
            mysqli_close($这个 - >连接);
        }
        赶上(异常$ E)
        {
            抛出$ê;
        }
    }
    公共功能查询($查询)
    {
        尝试
        {
            $这个 - > OPEN_CONNECTION();
            $结果= mysqli_query($这个 - >连接,$查询);
            返回$结果;
        }
        赶上(异常$ E)
        {
            抛出$ê;
        }
        $这个 - > close_connection();
    }
    公共职能fetchArray($查询)
    {
        $行= mysqli_fetch_assoc($查询);
        返回$行;
    }
    公共职能COUNT_ROWS($查询)
    {
        $行= mysqli_num_rows($查询);
        返回$行;
    }
    公共职能rows_affected()
    {
        $行= mysqli_affected_rows($这个 - >连接);
        返回$行;
    }
    公共职能created_id()
    {
        $行= mysqli_insert_id($这个 - >连接);
        返回$行;
    }
}
?>
 

Page.class.php

 < PHP
类网页
{
    私人$分贝;
    功能__construct($分贝)
    {
        $这个 - > DB = $分贝;
    }
    功能get_page($ seo_url)
    {
        $ SQL = $这个 - > DB->查询(SELECT * FROM page_details WHERE seo_url ='$ seo_url');
        $行= $这个 - > DB-> fetchArray($ SQL);
        返回$行;
    }
}
?>
 

的config.php

 < PHP
$配置=阵列();
$配置['DBTYPE'] ='的mysqli';
$配置['DBHOST'] ='localhost'的;
$配置['DBNAME'] ='名';
$配置['DBUSER'] ='用户';
$配置['DBPASSWORD'] ='密码';
$配置['absolute_path'] ='/var/www/vhosts/example.com/httpdocs';
$配置['website_root'] ='http://www.example.com/';
$配置['假'] ='';
?>
 

的init.php

 < PHP
require_once(配置/ config.php文件);
函数__autoload($将class_name)
{
    require_once(''。$配置['absolute_path'。班/ .class.php'$将class_name。');
}
$ DB =新的数据库($配置['DBHOST'],$配置['DBUSER'],$配置['DBPASSWORD'],$配置['DBNAME']);
?>
 

解决方案

我不知道你怎么想到要获得 __自动加载来叫(我不明白你叫新SomeClass的在code的任何地方),但它的使用 __自动加载自动包括面部应加载的类是一个好主意的,而你使用它的权利。

虽然你的code一些一般性意见:

  1. 我会用PDO来代替的mysqli直接 - 它有点更安全(SQL注入明智的),更面向未来,我认为它也很容易
  2. 我会检查要求 D文件试图要求它之前存在,并抛出一个漂亮的异常可以被捕获的应用程序,并报告在一个不错的方式。
  3. 您可能希望打印您的内容,而不是的print_r ,但我猜你做调试。

I have been looking into Dependency Injection.

  • Am I on to something or is it completely off?
  • Is the code good or bad - Dependency Injection or not?

The below code is the foundation for a CMS system

Right now there is a table called "page_details" with all the web pages stored in it.

Directory/file structure

.htaccess
index.php
classes/Db.class.php
classes/Page.class.php
config/config.php
config/init.php

.htaccess

# Mod rewrite enabled.
Options +FollowSymLinks
RewriteEngine on

# ---- Rules ----

RewriteRule ^([A-Za-z0-9-_]+)\.html$ index.php?page=$1 [NC,L]

index.php

<?php require_once ('config/init.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="imagetoolbar" content="no" />
    <title></title>
    <meta name="Description" content="" />
    <meta name="Keywords" content="" />
    <link href="/css/styles.css" media="screen" rel="Stylesheet" type="text/css" />
</head>
<body>
<?php
$page = new Pages($db);
print_r($page->get_page($_GET['page']));
?>
</body>
</html>

Db.class.php

<?php
class Db
{
    private $dbhost;
    private $dbuser;
    private $dbpassword;
    private $dbname;
    private $connection;
    public $query;
    function __construct($dbhost, $dbuser, $dbpassword, $dbname)
    {
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpassword = $dbpassword;
        $this->dbname = $dbname;
    }
    public function open_connection()
    {
        try
        {
            $this->connection = mysqli_connect($this->dbhost, $this->dbuser, $this->
                dbpassword, $this->dbname);
        }
        catch (exception $e)
        {
            throw $e;
        }
    }
    public function close($query)
    {
        try
        {
            mysqli_close($this->connection);
        }
        catch (exception $e)
        {
            throw $e;
        }
    }
    public function query($query)
    {
        try
        {
            $this->open_connection();
            $result = mysqli_query($this->connection, $query);
            return $result;
        }
        catch (exception $e)
        {
            throw $e;
        }
        $this->close_connection();
    }
    public function fetchArray($query)
    {
        $row = mysqli_fetch_assoc($query);
        return $row;
    }
    public function count_rows($query)
    {
        $row = mysqli_num_rows($query);
        return $row;
    }
    public function rows_affected()
    {
        $row = mysqli_affected_rows($this->connection);
        return $row;
    }
    public function created_id()
    {
        $row = mysqli_insert_id($this->connection);
        return $row;
    }
}
?>

Page.class.php

<?php
class Pages
{
    private $db;
    function __construct($db)
    {
        $this->db = $db;
    }
    function get_page($seo_url)
    {
        $sql = $this->db->query("SELECT * FROM page_details WHERE seo_url='$seo_url'");
        $row = $this->db->fetchArray($sql);
        return $row;
    }
}
?>

config.php

<?php
$config = array();
$config['dbtype'] = 'mysqli';
$config['dbhost'] = 'localhost';
$config['dbname'] = 'name';
$config['dbuser'] = 'user';
$config['dbpassword'] = 'password';
$config['absolute_path'] = '/var/www/vhosts/example.com/httpdocs';
$config['website_root'] = 'http://www.example.com/';
$config['dummy'] = '';
?>

init.php

<?php
require_once ('config/config.php');
function __autoload($class_name)
{
    require_once (''.$config['absolute_path'].'classes/' . $class_name . '.class.php');
}
$db = new Db($config['dbhost'], $config['dbuser'], $config['dbpassword'], $config['dbname']);
?>

解决方案

I'm not sure how you expect to get __autoload to be called (I don't see you calling new someclass anywhere in your code), but on the face of it using __autoload to automatically include classes that should be loaded is a good idea, and you're using it right.

Some general comments on your code though:

  1. I would have used PDO instead of mysqli directly - it somewhat safer (SQL injection wise), more future proof, and I think its also easier.
  2. I would check that the required file exists before attempting to require it, and throw a nice exception that can be caught by the application and reported in a nice way.
  3. you probably want to print your content and not print_r it, but I guess you do that for debugging.

这篇关于依赖注入在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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