Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - Call model function from another function within in the same model

Tags:

php

model

cakephp

I've got a CakePHP model with a few functions in it working well. Now I'm trying to write a new function that uses a few of the functions I've already written. Seems like it should be easy but I can't figure out the syntax. How do I call these functions I've already written within my new one?

Example:

<?php
public function getHostFromURL($url) {
    return parse_url( $http.$url, PHP_URL_HOST );
}
public function getInfoFromURL($url) {
    $host = getHostFromURL($url);
    return $host;
}

Result:

Fatal error: Call to undefined function getHostFromURL() in /var/www/cake/app/Model/Mark.php on line 151

I also tried something like:

<?php
public function getHostFromURL($url) {
    return parse_url( $http.$url, PHP_URL_HOST );
}
public function getInfoFromURL($url) {
    $host = this->Mark->getHostFromURL($url);
    return $host;
}

But got the same result.

Obviously my functions are much more complicated than this (otherwise I'd just reuse them) but this is a good example.

like image 422
Nick Avatar asked Jan 17 '23 15:01

Nick


2 Answers

If the function is in the same controller you access functions using

$this->functionName syntax.

You have wrong syntax below:

public function getInfoFromURL($url) {
    $host = this->Mark->getHostFromURL($url);
    return $host;
}

Should be:

public function getInfoFromURL($url) {
        $host = $this->getHostFromURL($url);
        return $host;
    }

If getFromHostUrl method is in the current class. http://php.net/manual/en/language.oop5.php

like image 147
dm03514 Avatar answered Jan 25 '23 15:01

dm03514


You simply need to call the other function like:

$host = $this->getHostFromURL($url);
like image 43
Adam Culp Avatar answered Jan 25 '23 16:01

Adam Culp