tkym
tkym

Reputation: 43

How can I call custom function from Model?

I'm using CakePHP3.0.5 and I'm just calling custom function from Model. But it shows Unknown method error. How can I call custom function from controller?

// Controller
class TopController extends AppController {
  public function initialize() {
    parent::initialize();
    $this->loadModel('TopRawSql');
  }

  public function showTop(){
    $data = TableRegistry::get('TopRawSql');
    $data->getTest(); // Unknown method error occur
  }
}

// Model
class TopRawSql extends Table {
  public function getTest() {
    return 'OK';
  }
}

I tracked the error message and found following the code. Does it mean, can't I use custom function name without 'find' prefix?

// vendor->cakephp->src->ORM->Table.php
public function __call($method, $args)
{
    if ($this->_behaviors && $this->_behaviors->hasMethod($method)) {
        return $this->_behaviors->call($method, $args);
    }
    if (preg_match('/^find(?:\w+)?By/', $method) > 0) {
        return $this->_dynamicFinder($method, $args);
    }

    throw new \BadMethodCallException(
        sprintf('Unknown method "%s"', $method)
    );
}

Upvotes: 1

Views: 293

Answers (2)

tjb74
tjb74

Reputation: 59

To answer your question, yes. The call() magic function is going to require every function within the body of a Model to be either a get* or set* function. But the code you quoted points you directly to the answer you're looking for: create a Behavior and call the function whatever you'd like.

Upvotes: -1

ndm
ndm

Reputation: 60463

Your table class name is wrong, all table classes must end in Table, ie TopRawSqlTable.

Given the wrong class name, I assume that the filename might be wrong too. And I don't know if you have the correct namespace set in the file, or any namespace at all since it's not shown in your question, but that needs to adhere to the conventions accordingly too, and would usually be App\Model\Table.

If the class for the requested alias cannot be found, then a generic instance of \Cake\ORM\Table will be used, which will then of course cause a failure as it won't have any of your custom code.

See also

Upvotes: 4

Related Questions