簡體   English   中英

CakePHP:在Controller中加載模型

[英]CakePHP: Loading Model in Controller

我想在我的控制器中加載我的模型。 該模型未與數據庫中的表關聯,因此可能無法遵循CakePHP的ORM。

我目前有以下代碼(這是我的模型):

<?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;
        }
}

我通過以下代碼(在控制器中)調用Model:

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

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

我無法以某種方式在我的控制器中調用它。 我一直收到以下錯誤:

應用程序中的某些Table對象是通過實例化“Cake \\ ORM \\ Table”而不是任何其他特定子類來創建的。

請嘗試更正以下表別名的問題:

流程

下面是一個示例,如何在CakePHP 3.x訪問沒有CakePHP ORM Model

在模型: Processes

在文件/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*/
    }
}

在控制器: Bookmarks

在文件/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
    }
}

以下是有關使用PSR-4自動加載的詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM