Codeigniter Undefined property: xxxx_model::$db only from Model - database

First the Model class:
class Xxxx_model extends Model
{
function XxxxModel()
{
parent::Model();
$this->load->database();
}
function isInDatabase()
{
// Please ignore the sql query, it's just to show some random sql code with results
11. $result = $this->db->query('SELECT * FROM someTable WHERE ...');
$numberOfRows = $result->num_rows();
...
return $test;
}
}
Now the controller:
function someLogic()
{
$this->load->model('xxxx_Model', 'xxxxModel'); // not necessary to specify
$this->xxxxModel->isInDatabase();
}
When I run this I get the error:
Severity: Notice --> Undefined property: Xxxx_model::$db .../xxxx_model.php line 11
I have no idea why this is. If I put the db code in the controller it seems to work, it's only with this setup in the model that it fails. I can't for the life of me figure out where the code is astray...

You have to load the db library first. In autoload.php add below code,
$autoload[‘libraries’] = array(‘database’);

add library 'datatabase' to autoload.
/application/config/autoload.php
$autoload['libraries'] = array(
'database'
);
Propably you're started new project, like me ;-)

To add to atno's answer:
class Xxxx_model extends Model
{
function XxxxModel() //<--- does not match model name Xxxx_model
{
parent::Model();
$this->load->database();
}
Basically, you are not constructing the class or the parent class Model. If you are on PHP5, you may use __construct(), otherwise you must match the class name exactly, regardless of what alias you load it with in your controller. Example:
class Xxxx_model extends Model
{
function __construct()
{
parent::__construct(); // construct the Model class
}
}
I may be mistaken (haven't used 1.x in a while), but if you construct the Model class, there's no need to load the database if you are using the default connection settings in config/database.php, it should already be loaded for you.

If function XxxxModel() isn't your constructor, you're not loading the database by calling $this->xxxxModel->isInDatabase();
Try autoloading the database library from within autoload.php, or create a proper constructor in your model.

Related

How can I call custom function from Model?

I'm using CakePHP3.0.5 and I'm just calling custom function from Model.
But it shows Unknown method error.
How can I call custom function from controller?
// Controller
class TopController extends AppController {
public function initialize() {
parent::initialize();
$this->loadModel('TopRawSql');
}
public function showTop(){
$data = TableRegistry::get('TopRawSql');
$data->getTest(); // Unknown method error occur
}
}
// Model
class TopRawSql extends Table {
public function getTest() {
return 'OK';
}
}
I tracked the error message and found following the code.
Does it mean, can't I use custom function name without 'find' prefix?
// vendor->cakephp->src->ORM->Table.php
public function __call($method, $args)
{
if ($this->_behaviors && $this->_behaviors->hasMethod($method)) {
return $this->_behaviors->call($method, $args);
}
if (preg_match('/^find(?:\w+)?By/', $method) > 0) {
return $this->_dynamicFinder($method, $args);
}
throw new \BadMethodCallException(
sprintf('Unknown method "%s"', $method)
);
}
Your table class name is wrong, all table classes must end in Table, ie TopRawSqlTable.
Given the wrong class name, I assume that the filename might be wrong too. And I don't know if you have the correct namespace set in the file, or any namespace at all since it's not shown in your question, but that needs to adhere to the conventions accordingly too, and would usually be App\Model\Table.
If the class for the requested alias cannot be found, then a generic instance of \Cake\ORM\Table will be used, which will then of course cause a failure as it won't have any of your custom code.
See also
Cookbook > CakePHP at a Glance > CakePHP Conventions > Model Conventions
Cookbook > Database Access & ORM > Table Objects
Cookbook > Configuration > Disabling Generic Tables
To answer your question, yes. The call() magic function is going to require every function within the body of a Model to be either a get* or set* function. But the code you quoted points you directly to the answer you're looking for: create a Behavior and call the function whatever you'd like.

Invoking cells directly from the controller

I am working with cakephp 3.1.7 and figuring out how to invoke view cells or retrieve cell data from the controller. I implemented basic cells with the help of cakephp docs and also http://josediazgonzalez.com/2014/03/20/view-cells/ document which is working fine. However, when I try to return cells directly from the controller I get the following error.
Error: Call to undefined method App\Controller\ProductsController::decorate()
This is what I have:
use Cake\View\Cell;
use Cake\ORM\TableRegistry;
class ProductupdateCell extends Cell
{
public function display($options = []){
if (!empty($options['displaylist'])) {
$this->set('productlist', $options['displaylist']);
return $this;
}else{
$category = $this->request->query['category'];
$this->loadModel('Products');
$query = $this->Products-> find()
-> where(['Products.category' => $category])
-> hydrate(false);
$productlist = $query->toArray();
$this->set('productlist',$productlist);
return $this;
}
}
}
In my controller,
<?php
class ProductsController extends Controller
{
use CellTrait;
public function view($id)
{
$products = $this->Products->findById($id);
$this->set('displaylist', $this->decorate('ProductupdateCell', $products));
}
}
Please correct me where I am going wrong. Is it efficient to use this to update my product list based on user input with ajax request? Can I selectively update the particular cell rendered in my view page? Is there any other method to update the cell directly. Please forgive me if this is a dumb question.
I am working with cakephp 3.1.7 and figuring out how to invoke view cells or retrieve cell data from the controller.
This is an architecturally wrong. They're supposed to be used from the view level.
If you want to have modular and abstracted controller logic either use the CRUD plugin. Or simply go for components. Components are packages of logic that are shared between controllers.
Error: Call to undefined method App\Controller\ProductsController::decorate()
There is no such method in the Controller, CellTrait nor the View class. I don't know from where you got that code, it's also not in the documentation of the cells.

CakePHP update public $uses = false; in action from same Controller

I'm writing an installation script for my CakePHP web application. I have a InstallController with 6 actions: step1, step2, step3, etc.
At step1 I'm handling Config/database.php creation. Because this file is empty and no datasource is available I have to set public $uses = false; in the InstallController.
At step2 the Config/database.php file is set so I should be able to make a connection to the datasource. This is also necessary because I want to update some database fields in the following steps.
Is it possible to update the public $uses = false; in every following steps after step1?
I'm using CakePHP version 2.3.5
Have you considered loading the model within the actions? So, something like:
<?php
App::uses('AppController', 'Controller');
class InstallController extends AppController {
public $uses = false;
public function step1() {
}
public function step2() {
$this->loadModel("Install");
$this->Install->callMethod();
}
}
In CakePHP 2.x models are lazy loaded, so as long as your step1 action doesn't try to make use of a model, you can safely declare the models in your controllers $uses property, they are not being constructed until your code actually makes use of them.
However, if for some reason you'd actually need to modify $uses, well then just do it, as mentioned models are lazy loaded, so you can modify $uses whenever you want and then access the models afterwards via magic properties on the controller.

how to use common function in helper and component In Cakephp

We are familiar with Components and Helpers in CakePHP.
I have an ABC Component and XYZ helper and both have same function (around 2000 lines total 4000 lines).
there is any way to use same function in Controller and .CTP files. it's not good to use same function 2 time.
any method so i can use Component/Helper function in Helper/Component without rewrite ?
same method into component and helper >>
Component
class DATAComponent extends Component {
public $components = array('Session', 'THmail');
public function UsaStateList()
{ /********/}
Helper
class LabHelper extends AppHelper {
public function UsaStateList()
{ /********/}
}
Well, you will have to rewrite something, it's not going to solve itself.
CakePHP is still PHP, so you can easily apply common patterns to keeps things DRY. The most straight forward way would probably be to move the shared functionality into an utility class that your component and helper can both use internally while leaving their public API unchanged.
Some of CakePHPs helpers do something similar, check for example the time helper.
http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html
http://book.cakephp.org/2.0/en/core-utility-libraries/time.html#CakeTime
Traits might be an option too, depending on the amount of functionality being shared and how much it is tied to the use in a component/helper.
I wanted to use a component inside a helper. So i came out with the following solution.
<?php
App::uses('AppHelper', 'View/Helper');
App::import('Component', 'MyComponent');
class MyHelperHelper extends AppHelper {
private $MyComponent = null;
public function __construct(View $View, $settings = array()) {
$collection = new ComponentCollection();
$this->MyComponent = new MyComponentComponent($collection);
parent::__construct($View, $settings);
}
public function myCustomFunction() {
return $this->MyComponent->myCustomFunction();
}
}
Simple Answer
For common functions across your application, add a Lib or Utility class.
app/Lib/MyClass.php
class MyClass {
public static function usaStateList() {
// ...
}
}
Then add this at the top of whichever file you want access to the function:
App::uses('MyClass', 'Lib');
And call your function wherever you like:
$myClass = new MyClass();
$states = $myClass::usaStateList();
Better Answer
It looks to me like your specific problem is that you want to be able to get a list of US states in both your controller and your view. The best way to do this is to have a database table of US states.
Create a table in your database called us_states.
Example SQL:
CREATE TABLE `us_states` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(20) NOT NULL,
`abbreviation` CHAR(2) NOT NULL
) ENGINE = MYISAM
Insert all the states as data in that table. You can find SQL dumps on the Internet which already have that for you (e.g. Like this one).
Create a UsState model in CakePHP.
/**
* Model for US States
*
* #package app.Model
*/
class UsState extends AppModel {
/**
* Default sort order
*
* #var string|array
*/
public $order = 'UsState.name';
}
What you can then do is access the states from your controller just by using the model.
/**
* Your Controller
*
* #package app.Controller
*/
class YourController extends AppController {
public function index() {
// Get a list of US states
$this->loadModel('UsState');
$states = $this->UsState->find('all');
}
}
And if you want to access those states in your View, then you should pass along that data as you normally would any other variables.
I imagine you would want to do that so you can have a select menu of US states, perhaps.
public function index() {
// Get a list of US states
$this->loadModel('UsState');
$states = $this->UsState->find('all');
// Make the states into an array we can use for a select menu
$stateOptions = array();
foreach ($states as $state) {
$stateOptions[$state['id']] = $state['name'];
}
// Send the options to the View
$this->set(compact('stateOptions'));
}
And in your view you can display a select menu for that like this:
echo $this->Form->select('us_state_id', $stateOptions);
I would go with a class in Lib folder. It is pretty clear how to deal with a library class that has only static methods. So, I omit this case. A workable solution for instantiating the class could be to create it in the controller and put it into the registry. If you really need to access CakeRequest, CakeResponse and CakeSession (take a note that CakeSession has many static methods, so you often do not need an instance of that class) from that class you can set it from the controller:
$MyLib = new MyLib();
$MyLib->setRequest($this->request); // optional
ClassRegistry::addObject('MyLib', $MyLib);
Then from the view or any other place you would just get an instance of MyLib from the registry:
ClassRegistry::getObject('MyLib');
or simply
$list = ClassRegistry::getObject('MyLib')->UsaStateList();
So, your class would be something like this:
// /Lib/MyLib.php
class MyLib {
public function setRequest(CakeRequest request) {...}
public function UsaStateList() {...}
}
ok you want to use a single function in component and helper, I can think of 3 things you can do:
Calling a function from the component in your helper.
Calling a function from a helper in your component.
Create a model or use an existing model where you put the function, and you can use this function in your component or your help.
Option numbre 3:
In your helper and component, you need import a model, assuming that your function be in a model "StateList":
how you call the funcion of the model "StateList" in your helper, so:
App::import("Model", "StateList");
$model = new StateList();
$model->UsaStateList();
how you call the funcion of the model "StateList" in your component, so:
$model = ClassRegistry::init('StateList');
$model->UsaStateList();
ans if you want use the same function in a controller just:
$this->loadModel('StateList');
$this->StateList->UsaStateList();

Symfony 2 FatalErrorException: Error: Call to a member function has() on a non-object

Symfony 2 typical problem, yet no clear response to it(I did some research).
Given the following "DefaultController" class which actually works:
<?php
namespace obbex\AdsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$connection=$em->getConnection();
$string="SELECT DISTINCT country_code FROM country_data";
$statement = $connection->prepare($string);
$statement->execute();
$result = $statement->fetchAll();
var_dump($result); //works not problem
die();
}
}
I want to delegate database calls to another class called "DatabaseController", the "DefaultController" now is set as following:
<?php
namespace obbex\AdsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use obbex\AdsBundle\Controller\DatabaseController; //new DatabaseController
class DefaultController extends Controller
{
public function indexAction()
{
$dbController = new DatabaseController();
$res = $dbController->getQuery();
}
}
and the "DatabaseController" is set as following:
namespace obbex\AdsBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DatabaseController extends Controller{
public function __construct() {
}
public function getQuery()
{
$em = $this->getDoctrine()->getEntityManager();
$connection=$em->getConnection();
$string="SELECT DISTINCT country_code FROM country_data";
$statement = $connection->prepare($string);
$statement->execute();
return $statement->fetchAll();
}
}
And this throw and the following error: FatalErrorException: Error: Call to a member function has() on a non-object in /home/alfonso/sites/ads.obbex.com/public_html/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php line 202
my mind is blowing right now because I am extending the exact same class "Controller". Why it is working in one case and not in the other?
Apparently it is a "container problem" that can be set trough a service according to a response in another thread or via extending the "Controller· class however does not work in this case.
First of all, you shouldn`t delegate database management to another controller, that's a bad practice.
Instead, you can inject a service containing all DB logic
Symfony2 Use Doctrine in Service Container
Or use a EntityRepository
http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
Regarding the issue with has() function, you are creating an instance of a Controller without any container on it. Therefore, when the controller tries to call $this->container->has() throws an error, as container is not defined.
I finally set the object caller and I requested the container service as follows:
on the services.yml file
service:
manage_ads:
class: obbex\AdsBundle\Classes\ManageAds
calls:
- [setContainer, ["#service_container"]]
on the main controller:
$ads_manager = $this->get('manage_ads');
$ads_manager->functionCallingTheRawQuery();
But I still use this optionally because now I am setting my queries from the repository of an entity rather than create my own objects (For now, I am new to symfony2)

Resources