简体   繁体   English

CodeIgniter MVC最佳实践-控制器

[英]CodeIgniter MVC best practice - Controllers

I have created a Google controller class which has a method distance() . 我创建了一个Google控制器类,该类具有一个distance()方法。 This uses Google's distance matrix to calculate the distance between two postcodes and returns the value. 这使用Google的距离矩阵来计算两个邮政编码之间的距离并返回该值。

Now I have another controller class called "Person". 现在,我有另一个名为“ Person”的控制器类。 I want to call the ${Google}->distance() method from within my Person class, to see how far this Person is away from a certain postcode. 我想从我的Person类中调用${Google}->distance()方法,以查看此Person与某个邮政编码之间的距离。

How would I achieve this and am I going about this the right way. 我将如何实现这一目标?

In case of the need to call another controller's method, you need to use modular extensions since CI itself does not support HMVC. 如果需要调用另一个控制器的方法,则您需要使用模块化扩展,因为CI本身不支持HMVC。

But in your case it's a bad design practice to place such logic in a controller, you need to make use of CI libraries (recommended since Google is a utility class) or models (if the class abstracts database interactions). 但是,在您的情况下,将此类逻辑放置在控制器中是一种不良的设计实践,您需要使用CI (由于Google是实用程序类而建议使用)或模型 (如果该类抽象了数据库交互作用)。

Simply place your class in application/libraries/Google.php and in your Person controller: 只需将您的类放在application/libraries/Google.phpPerson控制器中:

// 1. Load library via CI's loader:
// You may want to autoload the library
// @see application/config/autoload.php
$this->load->library('google'); 

// 2. Use library:
// NOTE: If it's a static class you need to call it as:
// Google::distance($postcode1, $postcode2);
$distance = $this->google->distance($postcode1, $postcode2);

What you ask about is less about MVC but more about how objects and instances in PHP work. 您所要求的不是MVC,而是有关PHP中对象和实例的工作方式的更多信息。

A most straight forward usage would be: 最直接的用法是:

$google = new Google();
$distance = $google->distance();

That is not high design, but the first step for you to get it to work. 那不是很高的设计,而是让您开始工作的第一步。 Later on you can decide if it isn't better to create the Google instance elsewhere, eg Codeigniter offers library loading mechanisms so you can hide away the details a little and can make it easier to access functionality. 稍后,您可以决定在其他地方创建Google实例是否更好,例如Codeigniter提供了库加载机制,因此您可以将细节隐藏一些并使其更易于访问功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM