CakePHP: Loading Model in Controller

蓝咒 提交于 2019-12-11 06:59:47

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/42836416/cakephp-loading-model-in-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!