CakePHP: Loading Model in Controller - php

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

Related

Laravel Eloquent Relationship with different foreign key

Laravel version is 7.0:
I have setup model relationships like this.
<?php
namespace App;
class Template extends Model
{
protected $fillable = ['header_id', 'content', 'name'];
public function header()
{
return $this->belongsTo('App\Header', 'header_id');
}
}
In controller I can get template object with header.
<?php
namespace App\Http\Controllers;
use App\Template;
class TemplateController extends Controller
{
public function show($id)
{
$template = Template::find($id);
}
}
Now I can use $template->header in view.
How can I pass different header_id and get header relationship object?
I would like to do as following:
<?php
namespace App\Http\Controllers;
use App\Template;
class TemplateController extends Controller
{
public function show($id, $temp_header_id)
{
$template = Template::find($id);
$template->header_id = $temp_header_id;
}
}
I want to get new header relationship in view:
Is there any way to return new header relationship when I do $template->header in view.
Thank you
Yes you can do what you are looking to do, but kinda defeats the relationship in the database. You can assign any id to $template->header_id and then load the relationship using that new value:
$template->header_id = 897;
// load the relationship, will use the new value
// just in case the relationship was already loaded we make sure
// to load it again, since we have a different value for the key
$template->load('header');
$template->header; // should be header with id = 897

Slim 3 & Eloquent call more than 1 tables in single Model file

Recently I've been learning to use Slim 3 and eloquent.
What I'm trying to do is this (if it's even possible that is)
So I have a Model.php file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Capsule\Manager as DB;
class Course extends Model{
protected $table = "courses";
public function GetCourses(){
}
}
?>
And my Controller.php
<?php
namespace App\Controllers;
use App\Models\Course;
use Slim\Views\Twig as View;
class CourseController extends Controller{
public function index($request,$response){
return $this->view->render($response,'course/CourseNew.twig',$data);
}
}
?>
So my question is inside the Model.php is it possible to call another table somehow?
I've already called mine with protected $table = "courses"; I kind of understand that the table i defined is for the whole Class but is there a way or a workaround?
The main idea here is that i have some database tables that are very small and are not worth making another Model files for them
If this is not possible what is the alternative?
Do I have to make another Model file and call it on top of my controller where i need it use namespace App\Models\"new_model";
I would recommend to separate the data structure from the data access logic. For example: put the code for the database queries into a Repository. A repository does not care where the data comes from (table x or table y).
Example
<?php
namespace App\Repository;
use App\Model\Course;
class CourseRepository extends Repository
{
public function __construct(Connection $db)
{
$this->db = $db;
}
public function findCourceById(int $courseId): ?Course
{
// execute query here
//$this->db->....
return $course;
}
public function findSomething(): array
{
// execute query here
//$this->db->....
return $rows ?: [];
}
}

Json Laravel Model

How to write model in Laravel without creating Database and with function getData that returns Json? Something like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Table extends Model
{
protected $table = 'table';
protected $fillable = [
'atribute1',
'atribute2',
'atribute3',
'atribute4'
];
}
But without database.
I would be grateful for help
You need to extend Model only if you're using Eloquent.
If you just need to get json data from somewhere, create usual class which gets data from somewhere and returns JSON:
class MyModel
{
public function getJsonData()
{
$jsonData = // get json data from somewhere
return $jsonData;
}
}
Register this class in composer.json file, run composer dumpauto and use your class:
$model = new MyModel();
$data = $model->getJsonData();

How to use Traits - Laravel 5.2

I'm new to Traits, but I have a lot of code that is repeating in my functions, and I want to use Traits to make the code less messy. I have made a Traits directory in my Http directory with a Trait called BrandsTrait.php. And all it does is call on all Brands. But when I try to call BrandsTrait in my Products Controller, like this:
use App\Http\Traits\BrandsTrait;
class ProductsController extends Controller {
use BrandsTrait;
public function addProduct() {
//$brands = Brand::all();
$brands = $this->BrandsTrait();
return view('admin.product.add', compact('brands'));
}
}
it gives me an error saying Method [BrandsTrait] does not exist. Am I suppose to initialize something, or call it differently?
Here is my BrandsTrait.php
<?php
namespace App\Http\Traits;
use App\Brand;
trait BrandsTrait {
public function brandsAll() {
// Get all the brands from the Brands Table.
Brand::all();
}
}
Think of traits like defining a section of your class in a different place which can be shared by many classes. By placing use BrandsTrait in your class it has that section.
What you want to write is
$brands = $this->brandsAll();
That is the name of the method in your trait.
Also - don't forget to add a return to your brandsAll method!
use App\Http\Traits\BrandsTrait;
class ProductsController extends Controller {
use BrandsTrait;
public function addProduct() {
//$brands = Brand::all();
$brands = $this->brandsAll();
return view('admin.product.add', compact('brands'));
}
}

Get all records in cakephp3 using TableRegistry?

My Demo Controller (DemoController.php):
<?php
namespace App\Controller;
class DemoController extends AppController
{
public function users()
{
$this->loadmodel('registration');
$result = $this->registration->getAllUsers();
$this->set('user_data',$result)
}
}
?>
My registration model (registration.php):
<?php
namespace App\Model;
use Cake\ORM\TableRegistry;
class Registration extends AppModel {
$articles = TableRegistry::get('registration');
public function getAllUsers()
{
return $query = $articles->find();
}
}
?>
My View:
path -- src/Template/Demo/users.ctp
but it's getting error like this (in below image) --
Your model should be named RegistrationsTable, and be in src/Model/Table/RegistrationsTable.php. Load it with loadModel('Registrations'). (It's your entity that should be named Registration.) To use your custom finder method, name the function findAllUsers, fix the signature per the documentation (should take two parameters: Query $query, array $options) and call it as $this->Registration->find('all_users');.
And why are you trying to initialize a $articles variable as the registrations model inside the registrations model (but outside of any function)? So much mess...

Categories