PHP Autoload - File Found - Class Fatal Error - php

I have a function on load that checks a users login status. Here is a small chunk of the code...
//
// user is logged in, get user info
$user = Model\User::getByKey($_COOKIE['ukey']);
if($user->field('id') >= 1 || !isset($status)) {
//
// establish google connection
Classes\Google\Google::construct($user->field('id'), $user->field('ga_account'));
...
I have an __autoload function which finds the path of the file perfectly fine. However, I get a fatal error because the "\Classes\Google\Google" class is not found.
new Google() ... is located at /classes/google/google.class.php. The file is there, the autload function has the correct file path but why isn't the class found?
I do not have any namespacing on this particular Google() class file. This is all custom built, not a third party framework.

1- use class_exists to make sure class is loaded .
2- if class not loaded , in google.class.php make a die , so u'll know file loaded or not.
3- if class loaded , make a new object here . the test it , so u can find the class definition is true or not.

Related

How to fix Symfony v2.8 "Creating/Configuring Services in the Container" 'autoloader expected class ...' error

For quite a while I've been trying to understand how to add my own library of functions that I want to use in my Web-App's different controller/bundles, but I just found that I needed to 'house' these functions a Symfony Service Container.
Unlike other computer languages, Services, are not a background process!
To get a better handle on this, I tried out the example in the Symfony v2.8 guide section on Creating/Configuring Services in the Container. I created the following file in the suggested directory:
<?php // <=== This was missing from the MessageGenerator.php file!
//
// Adding it to the file solved the autoloader error, and now the MessageGenerator
// class loads properly!
//
// src/AppBundle/Service/MessageGenerator.php
namespace AppBundle\Service;
class MessageGenerator {
public function getHappyMessage() {
$messages = [
'You did it! You updated the system! Amazing!',
'That was one of the coolest updates I\'ve seen all day!',
'Great work! Keep going!'
];
$index = array_rand($messages);
return $messages[$index];
}
}
Then I added the following to the services configuration file:
# app/config/services.yml
services:
app.message_generator:
class: AppBundle\Service\MessageGenerator
arguments: []
And then I placed the following lines in a controller/bundle that otherwise was previously working:
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
When I uploaded these files and ran the associated web-page, I got:
The autoloader expected class "AppBundle\Service\MessageGenerator" to be defined in
file "/var/www/vhosts/symfony2/vendor/composer/../../src/AppBundle/Service/
MessageGenerator.php". The file was found but the class was not in it, the class name
or namespace probably has a typo.
This message appears to be saying that the MessageGenerator.php file was found in the src/AppBundle/Service directory. However the class MessageGenerator was not defined in the MessageGenerator.php file because the file wasn't recognised as a php file due to the missing
The MessageGenerator.php file was missing
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
lines were executed, and $generatedMessage contained one of the array element messages, as expected.

CAS Authentication with Yii Framework

I'm facing some troubles trying to implement CAS Authentication with Yii framework. I downloaded the client classes and everything is working when I'm not using any framework, but when I try to integrate with Yii validation seems to not be working at all.
Can Anyone please describe the process to successfuly make a CAS validation with yii.
I put the clients files under /myapp/protected/vendor directory, then I put the following lines at the begining of the controller
Yii::import('application.vendors.*');
require_once('CAS/CAS.php');
Then I created the method for use my CAS Classes
public function casValidation()
{
phpCAS::client(CAS_VERSION_2_0, $server, $port, "/cas",false);
phpCAS::setNoCasServerValidation();
phpCAS::forceAuthentication();
if(isset($_REQUEST['logout']))
{
phpCAS::logout();
}
}
And Finally I try to validate from my index action
public function actionIndex()
{
$this->casValidation();
$this->render('index');
}
But in the web browser shows the following error
PHP warning
include(CAS_Client.php) [function.include]: failed to open >stream: No such file or directory
C:\app\vertrigo\Vertrigophp52\www\testyii\framework\YiiBase.php(427)
Am I Missing something? What should I do to make things work?
Finally I got it working, turns out that I had made a couple of mistakes.
First of all I should not have been using require statement. The reason for this is that Yii alredy take care of loading the classes via the import method as shown below.
Yii::import('application.vendor.CAS.*')
Second thing I had a typo on this import, I had
/* This is wrong */
Yii::import('application.vendors.CAS.*')
instead of
/* This is correct */
Yii::import('application.vendor.CAS.*')
So Yii was looking for the vendors directory which does not exist.
And finally, to successfully use the import method the file containing your class has to have the same name. So if you have a class name user you have to name your file user.php in order to Yii can load it successfully.

Writing a cron job using CodeIgniter CLI?

Hi I am facing some problems in writing a cron job using CI CLI way. My application has a controller name called manager.php in that there is method called check_status where I am gonna get all the order_ids using one model function. Ever order_id row had a status filed in database which either success or failure.
I have an api if i pass order_id to that it will tell whether order is successfully delivered or not. But here comes the problem I have below line in controller in the top.
<?php if(! defined('BASEPATH') ) exit("NO Direct Script Access Allowed"); ?>
So when i try to run method check_status from CLI in CI it gives me an error stating NO Direct Script Access Allowed.
This is the way i called above method php application/controllers/manager.php check_status
So i decided like this i created an another class file called cron_job.php in that i didn't keep the above error line "No Direct Script Access Allowed". I thought it will give access now when i try to run but it doesn't give an error and even output also.
This is the class which i created and method in that.
<?php
class Cron_job extends CI_Controller {
public function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}
}
?>
I run this controller form CLI like this php application/controller/cron_job.php message
Note: I am in ROOT directory.
No Output at all. So i tried in another way like this php index.php application/controller/cron_job.php message
Now it gives me error stating that Error 404 page not found.
What i tried in another way now i created a file in views folder and in that i am calling old controller/method url like below.
$result = file_get_contents("http://application_path/controller/method");
echo $result;
Now i am getting output which i defined in the method check_status in manager.php controller.
But here comes another problem now after the above line i will get an array output which had all the order_ids.
I am gonna send this each id to a api to check status. If it is failure it will check whether it is delivered or not. If it's done i need to update that status in the database against that order_id. But now i am in view file, is it possible to call a model file from the view file or is there any way to do this.
Any help?
Note: There is no syntax errors in any controller or any method , which are fully verified and working normally when i am accessing using urls.
You need to read the CodeIgniter help section on Running via the Command Line. It's very easy. Your original approach was correct. But you do not call your controller method directly by its path, instead CD to your project root and then the call the index.php file with the controller and method as parameters.
// This is how you call CI via the command line.
// Use spaces between index.php and your arguments.
$ php index.php <controller> <method> [params]
// And in your instance
$ php index.php manager check_status [param1 param2 param3]
Depending on your host you may need to call the PHP version compiled for CLI.
the ci helper will help you in this.
1 ) Create a helper & create a function in it, that calls your model function
function getUserDetails($userId = '') {
$CI = & get_instance();
$getUserDetailsByUserId = $CI->user_model->getUserDetailsByUserId($userId);
return $getUserDetailsByUserId;
}
2) Now you can call getUserDetails($userId); in your view.

Unable to access library function in codeigniter

I am noob in codeigniter. I used an external class file for getting the length of an audio file. I put the file in application/libarary directory. After googling and reading documentation I tried two things for accessing the libarary function which I have mentioned under the codeigniter problem.
Working Demo from the External Library File
require ('classAudioFile.php');
$filename = "40f11852c2314cdf1d06308f07de3b1c.mp3";
$AF = new AudioFile;
$AF->loadFile($filename);
echo $AF->wave_length;
CodeIgniter Problem
$filename = "./uploads/audio_files/347f21502e9b27fac4707b07c3c15eb7.mp3";
$CI =& get_instance();
$CI->load->library('AudioFile');
$CI->AudioFile->loadFile($filename);
$filename = "./uploads/audio_files/347f21502e9b27fac4707b07c3c15eb7.mp3";
$this->load->library('AudioFile');
$this->AudioFile->loadFile($filename);
I am getting Call to a member function loadFile() on a non-object in D:\wamp\www\webcartz\application\modules\playlist\controllers\admin.php on line 149 this is the actuall error.. can any body please help. I tried to call it in both Controller and View file.
to normalize everything try the following:
the AudioFile.php you put in the library folder, make the file name all lower case, like audiofile.php. if it is called classAudioFile.php, rename it to simply audiofile.php
check that there is a class AudioFile in audiofile.php.
change the AudioFile in the load->library to all lowercase
change the AudioFile in the $this->AudioFile-> to all lowercase
if it still does not work change the name of the class (not the file) to Audiofile, capital A, lower case f.
Also, there should be an default - no parameter constructor in the class Audiofile. like this:
public function __construct()
{
// you can put some code here if you want
}

Joomla: Call helper function from within a model?

I'm starting off with both php and Joomla development, and finding it difficult working within Joomla to do some fairly simple stuff. Went through the Joomla MVC example and Lynda (and have built a few simple views so far).
I have a helper file/class/function that outputs all the userids that exist in the "completed" table so I can display a link for either a new record based on that user or edit an existing user's record.
I've already used a different function in this helper file successfully in a different part of the component ( Joomla: Write and call a helper function in a component ).
When I do the same thing in the model, I'm getting this: "Fatal error: Call to protected method JModel::_createFileName() from context 'JView' in C:\wamp\www\ilplocal\libraries\joomla\application\component\view.php on line 773". When I try it in the view, works fine - but I need the output in the model.
Code:
lookups.php
abstract class LookupHelper {
public function other_functions($vars){
...
}
public function completions_exist() {
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->SELECT(' #__completed.completed_userid as UserID');
$query->FROM (' #__completed');
$query->GROUPBY (' #__completed.completed_userid ');
$db->setQuery($query);
$result = $db->loadResultArray(0);
return $result;
}
}
In the model:
$completions_exist = Jview::loadHelper('lookups');
$completions_exist = LookupHelper::completions_exist();
This line is throwing the error: $completions_exist = Jview::loadHelper('lookups');
I've found some really vague references to something called JLoader::register to pull in helper functions but can't find any good documentation on that in Joomla except for everyone saying to just use that. SO I tried using it like so:
JLoader::register('LookupHelper', dirname( JPATH_COMPONENT_ADMINISTRATOR).DS.'helpers'.DS.'lookups.php');
$completions_exist = LookupHelper::completions_exist();
which throws this error: "Fatal error: Class 'LookupHelper' not found in C:\wamp\path\to\model\not\to\lookups.php. Tried manipulating the JLoader::register(everything here) and it doesn't effect the path of the error message.
Thoughts? Why does it work in a view and not in the model? How do I use the helper functions within a model?
Thanks!
#####EDIT
Thanks to #cppl looks like it's a path issue with the second bit of code. Also I read that the .DS. notation will be phased out in future versions - so the code that's working is:
JLoader::register('LookupHelper', JPATH_COMPONENT_ADMINISTRATOR.'/helpers/lookups.php');
$completions_exist = LookupHelper::completions_exist();
Lets break this down:
In Joomla! your components helper file should be in `/mycomponent/helpers/lookup.php'
JLoader:: is the Joomla! way to do it, but you could just as easily use PHP's require_once eg. require_once JPATH_COMPONENT_ADMINISTRATOR.'/helpers/myfunctions.php';
Is your path right? - you're providing dirname(JPATH_COMPONENT_ADMINISTRATOR).DS.'helpers'.DS.'lookups.php' but you've wrapped the path to your component in dirname which will the parent element of the path only. So JLoader is looking in /administrator/helpers/lookups.php.
JPATH_COMPONENT_ADMINISTRATOR is initialised as part of Joomla!'s renderComponent() call in it's JComponentHelper class if you apply dirname to it when it's not setup you will get back a dot (ie. current directory) so in the model you could would be passing ./helpers/lookups.php to the JLoader call.
You can call helper within model by following method:
JLoader::import('helpers.events', JPATH_COMPONENT);
this will include the file helpers/events.php from the component directory.
$_helper = new EventsHelper();
echo $_helper->getAnyInsideMethod();exit;

Categories