Cakephp throws undefined method but the method exists - cakephp

i created custom classes in the plugin. This class contains several methods. Unfortunately sometimes crashes on Exception
Error: Fatal Error (1): Call to undefined method DateTools::getUserDateFromSQL() in ...
but this method is in the class :(. Unfortunately an error occurs infrequently and can not even repeat it.
My class in plugin Tools (folder Lib)
class DateTools {
public function getUserDateFromSQL($value) {
if(empty($value)) return $value;
return Date("d.m.Y H:i", $this->getDateFromSQLDate($value));
}
...
...
...
The place where source crash.
App::import('DateTools', 'Tools.Lib');
class SomeController extends SomeParentAppController {
public function someMethod($arraysDate) {
$dateTools = new DateTools();
$result[$key] = $dateTools->getUserDateFromSQL($value);
...
...
...
Thanks for help

The syntax used to include the class is incorrect
You could use App::uses instead of App::import
App::uses('DateTools', 'Tools.Lib');
Syntax for App::import()
Syntax for App::uses()

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.

Unit testing getting error class could not be found

I have a class for dynamoDB in location
src/Dynamo/shop.php
My class looks like below
<?php
namespace App\Dynamo;
class Shop
{
-----
}
?>
I am trying to implement unit test for this class, So I have created a folder class dynamo in below location.
app/cake/tests/TestCase/Dynamo
In Dynamo folder I have created a class with file name ShopTest.php
For create a unit testing I have written this class like below
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Dynamo;
use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;
class ShopTest{
public function setUp()
{
$this->shop = new Shop;
}
public function testconnectDynamoDB()
{
debug($this->shop->connectDynamoDB());
$this->assertNotEmpty($this->shop->connectDynamoDB());
}
}
Now after run phpunit command
vendor/bin/phpunit tests/TestCase/Dynamo/ShopTest.php
I am getting
Class 'App\Test\TestCase\Dynamo\ShopTest' could not be found in '/var/www/html/tests/TestCase/Dynamo/ShopTest.php'.
Class is present in this location , Why I am getting Class could not be found ?
root#0ceda1df4444:/var/www/html# cd /var/www/html/tests/TestCase/Dynamo/
root#0ceda1df4444:/var/www/html/tests/TestCase/Dynamo# ls
ShopTest.php
root#0ceda1df4444:/var/www/html/tests/TestCase/Dynamo# cat ShopTest.php
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Dynamo;
use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;
class ShopTest{
Also I am trying to run all test case by below command , I am getting a warning.
root#0ceda1df4444:/var/www/html# vendor/bin/phpunit
PHPUnit 9.5.9 by Sebastian Bergmann and contributors.
Warning: Your XML configuration validates against a deprecated schema.
Suggestion: Migrate your XML configuration using "--migrate-configuration"!
No tests executed!
There is no test class
The error message there is a bit confusing, but the crux is this is not a test class:
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Dynamo;
use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;
class ShopTest{ # <--
It is just a class (which coincidentally has the word Test in its name).
Compare to an example from the documentation:
namespace App\Test\TestCase\View\Helper;
use App\View\Helper\ProgressHelper;
use Cake\TestSuite\TestCase;
use Cake\View\View;
class ProgressHelperTest extends TestCase # <--
{
To be detected as a test the class must extend TestClass - therefore to correct this:
...
use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;
class ShopTest extends TestCase # <--
{
With that change the test class will load and some easier-to-solve problems will become apparent:
$ vendor/bin/phpunit tests/TestCase/Dynamo/ShopTest.php
PHP Fatal error: Declaration of ShopTest::setUp() must be compatible with Cake\TestSuite\TestCase::setUp(): void in ~/repos/cakephp/app/tests/TestCase/Dynamo/ShopTest.php on line 11
Fatal error: Declaration of ShopTest::setUp() must be compatible with Cake\TestSuite\TestCase::setUp(): void in ~/repos/cakephp/app/tests/TestCase/Dynamo/ShopTest.php on line 11

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)

CakePHP: "Class 'HttpSocket' not found"

I'm trying to use CakePHP's HttpSocket class to make an API call, but I can't seem to get it to include the class. It seems pretty simple, so I can't see where I might be going wrong, but here's what I have:
At the top of the controller:
class RetailersController extends AppController {
public $uses = array(...lots of classes..., 'HttpSocket', 'Network/Http');
Then in the function itself:
$HttpSocket = new HttpSocket();
And when I run that, I get:
Fatal Error
Error: Class 'HttpSocket' not found
As I said, there's not much to this, so I can't see that there's much that can go wrong - but I seem to have managed it! What can I try next?
I'm using CakePHP 2.4.
Add this before class definition:
App::uses('HttpSocket', 'Network/Http');
This variable is only for models: $uses

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

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.

Resources