简体   繁体   中英

CodeIgniter MVC best practice - Controllers

I have created a Google controller class which has a method distance() . This uses Google's distance matrix to calculate the distance between two postcodes and returns the value.

Now I have another controller class called "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.

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.

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).

Simply place your class in application/libraries/Google.php and in your Person controller:

// 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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