【发布时间】:2016-02-14 20:51:16
【问题描述】:
我正在尝试制作我最好的 OOP 代码来解析来自数据库的数据的对象,因此我创建了一个从 hooks 文件夹调用 class AppAutoLoadObjects 的钩子。
config/hooks.php
$hook['pre_system'][] = array(
'class' => 'AppAutoLoadObjects',
'function' => 'initialize',
'filename' => 'AppAutoLoadObjects.php',
'filepath' => 'hooks'
);
钩子/AppAutoLoadObjects.php
class AppAutoLoadObjects
{
public function initialize()
{
spl_autoload_register(array($this,'autoloadCoreObjects'));
}
public function autoloadCoreObjects($class)
{
$path = array(
'objects/',
);
foreach($path as $dir) {
if (file_exists(APPPATH.$dir.$class."_Object".'.php'))
require_once(APPPATH.$dir.$class."_Object".'.php');
}
}
}
正如您在代码中看到的,我有一个 objects 文件夹,我需要对象解析器。
所以如果我有models/Products_model.php,autoloadCoreObjects 会自动加载objects/Products_Object.php。
然后在我的Products_model.php 中使用每个函数:
public function select_by_limit($start, $limit, $resolution) {
..........................................
$query = $this->db->get_compiled_select();
$result = $this->db->query($query);
return $result->custom_result_object('Products_Object');
}
所以我的带有数据库项目的对象在Products_Object.php中解析
class Proprietati_Object
{
private $_resolution;
public function __construct($resolution = 270){
$this->_resolution = $resolution;
$this->_ci = get_instance();
}
//here is where I check if any image in database and if not give a default
public function image(){
if($this->image_name):
return base_url('assets/uploads/'.$this->id_proprietate.'/'.$this->image_resolution());
else:
return base_url('assets/images/no-product-image-available.png');
endif;
}
//here is where I load a small part of view as string because I must show in view different html code for each product_type
public function get_block_caracteristics(){
if($this->product_type == 'apartament')
return $this->_ci->load->view('blocks/apartament', array('product' => $this), TRUE);
elseif($this->product_type == 'land')
return $this->_ci->load->view('blocks/land', array('product' => $this), TRUE);
}
//here is where I set the image resolution and depends on each page where I show the products. E.g. 100, 200, 500
private function image_resolution() {
$image = explode('.', $this->image_name);
return $image[0].'_'.$this->_resolution.'.'.$image[1];
}
}
通过这种方法,我的控制器干净了,我只使用:
$products = $this->products->select_by_limit(0, 10);
$data['products'] = $products;
然后在视图中:
<?php foreach($products as $product): ?>
<?= $product->image() ?>
<?= $product->get_block_caracteristics() ?>
<?php endforeach; ?>
我的问题是如何将模型中的 $resolution 变量传递给 Products_Object 构造函数?或者我的方法不是很好?
我现在这是一个非常详细的问题,但我很久以前就在处理这个问题,我的目的是开始使用干净的控制器和模型进行编码。我使用的框架是 CodeIgniter。
【问题讨论】:
-
我已经解释了这个线程中的所有内容forum.codeigniter.com/thread-63496.html
-
是的,但在上次讨论中,我不明白如何将 $resolution 传递给类,为什么不能将 html 的某些部分作为字符串加载到该类中?如果不是加载部分 html 的好方法,我可以在哪里?
-
我发布了一个答案,但如果您了解我在 CI 论坛上的示例中所做的 - 您自己就会知道答案...
标签: php codeigniter oop model-view-controller