Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Models in controllers

I have a controller that starts off

namespace Controllers;

use \Models\Organisation as Organisation;

class OvniOrg extends \Phalcon\Mvc\Controller {


    //just says hello and lets you know you are in the right place.
    public function hello(){

    echo "Hello!";    

    }

    ///get a list of all organizations
    public function listOrganizations() {

    $phql = "SELECT * FROM Organisation";
    $organisation = $this->modelsManager->executeQuery($phql);

    $data = array();
    foreach ($organisation as $org) {
        $data[] = array(
            'Organisation ID'  => $org->id, 
            'Organisation Name'  => $org->orgName,
            'orgCurrAccessToken'  => $org->orgCurrAccessToken
        );
    }

    if (empty($data)) {
   $data[] = array(
            'status' => "OK",
            'result' => "No data returned from the server for organisations.",
            );
}

    echo json_encode($data, JSON_PRETTY_PRINT);
    }

The controller cannot seem to find the model as I am getting an error that the model cannot be found. I am using Autoload to get the models dir in the bootstrap file.

Model "Organisation" could not be loaded.

I am fairly new to MVC so I am not sure if this is even the correct way to process data. I admit ignorance,

Thanks

T

I believe your application is using a single module

    use \<namespace>\Models\Organisation as Organisation;

Remember to use the namespacing well. http://docs.phalconphp.com/en/latest/reference/namespaces.html



2.9k
Accepted
answer

This worked. I needed to add use to the top of the page and then point to the model. Not sure if you can use PHQL but this works much better. Hope this helps another noob!

namespace Controllers;
use \Models\Organisation;

class ExampleController extends \Phalcon\Mvc\Controller {


    public function pingAction() {

        echo "pong";
    }

    public function testAction($id) {
        echo "test (id: $id)";
    }

    public function skipAction($name) {
        echo "auth skipped ($name)";
    }

    public function getOrgAction(){

        $organisation = Organisation::findFirst();

    $data = array();
    foreach ($organisation as $org) {
        $data[] = array(
            'Organisation ID'  => $org->id, 
            'Organisation Name'  => $org->orgName,
            'orgCurrAccessToken'  => $org->orgCurrAccessToken
        );
    }

    if (empty($data)) {
   $data[] = array(
            'status' => "OK",
            'result' => "No data returned from the server for organisations.",
            );
}

    echo json_encode($data, JSON_PRETTY_PRINT);


    }
}