2

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.

3
  • 3
    rather than creating a controller, you could create a library for distance calculating script and call the library from whichever controller you want to... Commented Dec 24, 2012 at 11:20
  • Or you can simply create a custom helper Commented Dec 24, 2012 at 11:22
  • Thanks all, I am also new to CI, which is why I missed the whole libraries thing. Commented Dec 24, 2012 at 11:44

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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, e.g. Codeigniter offers library loading mechanisms so you can hide away the details a little and can make it easier to access functionality.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.