简体   繁体   中英

CakePHP: Loading Model in Controller

I would like to load my Model in my Controller. The model is not associcated with a table in the database, thus it is probably not able to follow CakePHP's ORM.

I have the following code currently (this is my Model):

<?php
namespace App\Model\Json;

use Cake\Filesystem\File;

 class Processes
 {

        public static function getData()
        {

            $file = new File('process_data.json');
            $json = $file->read(true, 'r');

            $jsonstd = json_decode($json);

            // remove STD classes
            $json2array = json_decode(json_encode($jsonstd), true);

            $cpu = array();

            foreach ($json2array as $key => $row)
            {
                $cpu[$key] = $row['cpu_usage_precent'];
            }
            array_multisort($cpu, SORT_DESC, $json2array);
            // return data
            return $json2array;
        }
}

I call the Model through the following code (in the controller):

$json2array = $this->Processes->getJson();

$this->set('data', $json2array);

I am not able to call it in my Controller somehow. I keep getting the following error:

Some of the Table objects in your application were created by instantiating "Cake\\ORM\\Table" instead of any other specific subclass.

Please try correcting the issue for the following table aliases:

Processes

Here is an example, How to access Model without CakePHP ORM in CakePHP 3.x

In Model : Processes

In the file /path_to/src/Model/Table/Processes.php

namespace App\Model\Table; #Define the namespace

use Cake\Filesystem\File;

class Processes{
    public static function getData(){
       /*Your codes here*/
    }
}

In Controller : Bookmarks

In the file /path_to/src/Controller/BookmarksController.php

namespace App\Controller;

use App\Model\Table\Processes; #Using PSR-4 Auto loading 
use App\Controller\AppController;

class BookmarksController extends AppController{
    public function tags(){
        $data = Processes::getData(); #Now you can assess Data
    }
}

Here is the details about Auto loading with PSR-4

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