Phalcon's universal class loader can't find my class - php

As a total php and phalcon newbie, I'm trying to use the recommended universal class loader using this code:
$loader = new \Phalcon\Loader();
// Register some directories
$loader->registerDirs(
array(
"php/assistants/"
)
);
// register autoloader
$loader->register();
$test = new dbAssistant();
as I understand I have to reffer to the php file as a class what I have inside of php/assistants/dbAssistant.php is the following code, trying to connect to a database:
<?php
function connect() {
$connection = new Phalcon\Db\Adapter\Pdo\Mysql(array(
'host' => 'localhost',
'username' => 'root',
'password' => 'tt',
'dbname' => 'testdb',
'port' => '3306'
));
echo 'Connected!!!';
}
again what I understand is that I have to refer to dbAssistant.php as a class and that's why I'm using $test = new dbAssistant();, but it gives me the following error:
Fatal error: Class 'dbAssistant' not found in /var/www/html/test/test.php on line 18
I know that it seeme normal, but the strange thing is that if I remove the connect() function and place the code out of it, I can see the Connected!!! echo, but it is followed by the same(above) error. I know that I'm missing something really small here, but as a complete php newbie, I really can't spot the problem.
Can you give me a push?

php/assistants/dbAssistant.php is not a class but a plain Php file. There should be a class in there with the name dbAssistant.
class dbConnect {
public function connect() {
///Do your stuff
}
}

Related

Fatal error: Class 'medoo' not found

I am using slim framework 2 with medoo via composer, i am making singleton for medoo but when i call the medoo class to configure my db info, so it gives me the fatal error like below
Fatal error: Class 'medoo' not found in C:\xampp\htdocs\school\s.php
on line 5
below is my s.php file
<?php
require 'vendor/autoload.php';
$app = new\Slim\Slim();
$app->container->singleton('test',function () use ($app) {
return new medoo([
'database_type' =>'mysql',
'database_name' =>'mydb',
'server'=> 'localhost',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'option' => [
PDO::ATTR_CASE=>PDO::CASE_NATURAL
]
]);
});
$app->get('/', function () use($app) {
echo "<center><b><a href='#' target='_blank' >WELCOME TO TESTING PAGE</a></b></center>";
$sth = $app->test->insert("t", ["id" =>1, "name" => "dsfdsf"]);
var_dump($sth);
});
$app->run();
?>
If i check the composer.json file then i find slim and medoo both are there, i am not getting why this fatal error is coming please help me
Two things:
you need to import the class
your class name should be case-sensitive
That is:
<?php
use Medoo\Medoo;
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->container->singleton('test',function () use ($app) {
return new Medoo([
// ...
]);
});
For reference, see:
http://php.net/manual/en/language.namespaces.php
https://github.com/catfan/Medoo/tree/v1.4.5

Silex with Doctrine and PHP classes

So, I'm trying to get around in Silex. Just learn the way it works and I'm trying to use Doctrine in it. I can use it on the index.php, but I'd also like to use it in my classes. These lines are used in the normal root file (index.php):
$images = $app['db']->prepare("SELECT * FROM images");
$images->execute();
$images = $images->fetchAll(\PDO::FETCH_CLASS, \AI\Models\Image::class);
So that would give me the ability to do something with the images. But I don't want to work this way. I'd like classes to do it all for me, so that I just script some methods which do all the hard work for me. That would let me just run one line for each Route in index.php
The problem is that I don't know how to connect with Doctrine from inside my classes. Because there is no '$app' in there. I think it would be weird to start the app inside of a class.
So let's say I wanted to create a user class. This SQL would give me all the users: "SELECT * FROM users". But how would I use Doctrine inside the User class?
<?php
namespace Models;
class User {
public function find($user){
if($user) {
$field = (is_numeric($user)) ? 'id' : 'username';
$sql = "SELECT * FROM users";
$data = // RUN QUERY $SQL
if($data->count()) {
$this->_data = $data->all();
return true;
}
}
return false;
}
}
In your index.php follow these steps.
Create instance of the silex application:
$app = new Silex\Application();
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
Set the database configuration:
$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
'driver' => 'driver',
'dbname' => 'dbname',
'host' => 'host',
'user' => 'user',
'password' => 'pass',
'charset' => 'charset',
'port' => 'port'
);
Connect to database:
$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);
Now you have different ways to make this db instance accessible throughout your app. You can whether make a global variable adding the instance in it:
global $dbcon;
$dbcon = $conn;
Or simply add it to the $app itself:
$app['dbcon'] = $conn;
Furthermore you might want to add a constructor to your models like this:
public function __construct($db)
{
$this->db = $db;
}
You would need to inject those instances in your controller.
I looked through the docs real quick and think I found what you need.
Here is a link to the documentation page : http://silex.sensiolabs.org/doc/2.0/providers/service_controller.html.
the documentation page explains everything you need to know to get what you want to achieve.

Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable

I'm using Eloquent in combination with Slim Framework to build a small API. For some reason, I am getting this error, and I can't locate the problem:
Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable.
Database settings are correct. This error is thrown in my staging environment on the server. Locally, with MySQL 5.6.29, it works perfectly. Although I don't think it's related to MySQL 5.7 because I have another app running on the same server with the same version of Eloquent.
Can anyone point me in the right direction?
I'm using:
Eloquent Version: 5.3.23
PHP Version: 5.6.28
Database Driver & Version: MySQL 5.7.16
Backtrace
/path/to/app/shared/vendor/illuminate/container/Container.php:644
Illuminate\Container\Container -> make
/path/to/app/shared/vendor/illuminate/database/Connectors/ConnectionFactory.php:130
call_user_func
/path/to/app/shared/vendor/illuminate/database/Connection.php:964
Illuminate\Database\Connection -> getPdo
/path/to/app/shared/vendor/illuminate/database/Connection.php:832
Illuminate\Database\Connection -> reconnectIfMissingConnection
/path/to/app/shared/vendor/illuminate/database/Connection.php:717
Illuminate\Database\Connection -> run
/path/to/app/shared/vendor/illuminate/database/Connection.php:350
Illuminate\Database\Connection -> select
/path/to/app/shared/vendor/illuminate/database/Query/Builder.php:1648
Illuminate\Database\Query\Builder -> runSelect
/path/to/app/shared/vendor/illuminate/database/Query/Builder.php:1634
Illuminate\Database\Query\Builder -> get
/path/to/app/shared/vendor/illuminate/database/Eloquent/Builder.php:632
Illuminate\Database\Eloquent\Builder -> getModels
/path/to/app/shared/vendor/illuminate/database/Eloquent/Builder.php:327
Illuminate\Database\Eloquent\Builder -> get
/path/to/app/shared/vendor/illuminate/database/Eloquent/Builder.php:297
Illuminate\Database\Eloquent\Builder -> first
...
I'm suspecting it has something to do with an unregistered error handler:
github link
But how can I register the custom error handler when not using Laravel?
The solution of #patricus can be implemented as follows:
// bootstrap Eloquent ORM
$container = new Container();
$container->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler'
, 'My\Custom\DatabaseExceptionHandler'
);
$factory = new ConnectionFactory( $container );
$connection = $factory->make([
'driver' => 'mysql'
, 'host' => App::config( 'database_host' )
, 'database' => App::config( 'database_name' )
, 'username' => App::config( 'database_user' )
, 'password' => App::config( 'database_password' )
, 'charset' => App::config( 'database_charset' )
, 'collation' => App::config( 'database_collate' )
, 'prefix' => ''
]);
$resolver = new ConnectionResolver();
$resolver->addConnection( 'default', $connection );
$resolver->setDefaultConnection( 'default' );
// initialize connection
Model::setConnectionResolver( $resolver );
You should be able to access the container to register your own exception handler through the capsule.
$capsule = new \Illuminate\Database\Capsule\Manager();
$capsule->getContainer()->singleton(
\Illuminate\Contracts\Debug\ExceptionHandler::class,
\Your\ExceptionHandler\Implementation::class
);
If you want a real quick, very dumb, exception handler, you can use this:
class DumbExceptionHandler implements \Illuminate\Contracts\Debug\ExceptionHandler
{
public function report(Exception $e)
{
//
}
public function render($request, Exception $e)
{
throw $e;
}
public function renderForConsole($output, Exception $e)
{
throw $e;
}
}
NB: untested. I believe this should work looking at the code.
In my case it was permissions issue of system user who executes php command.
Please make sure that your xampp server and the database server is working and running.

Add Doctrine DBAL into own php project

Trying to add Doctrine DBAL into my own project to use it to access my db etc. I don't have composer and i never used it. This is what i am trying to do according to the docu:
use Doctrine\Common\ClassLoader;
class Connection
{
var $connection;
//Constructor
public function __construct()
{
require_once "doctrine/Common/ClassLoader.php";
$classLoader = new ClassLoader('Doctrine', 'doctrine');
$classLoader->register();
$config = new Configuration();
$connectionParams = array(
'dbname' => 'mydb',
'user' => 'root',
'password' => "",
'host' => 'localhost',
'driver' => 'pdo_mysql',
);
$this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
}
}
This is taken from here:
-http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html
and:
- http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/introduction.html
I have the Common and DBAL folder added into my project
My folder structure looks like this:
root
doctrine
DBAL
Common
php stuff
index.php (where connection.php) is executed
So what happens is that i either get "Cannot find class XY" or something similar, based upon what i change on the code. I never am able to execute it as it should following the tutorial.
What am i doing wrong here?
I just want to have the connection object, where i can start doing my stuff like useing the query builder etc...
I am completely lost here...
UPDATE: Installed composer as requested and have this Code now:
use Doctrine\DBAL\Configuration;
class Connection
{
var $connection;
//Constructor
public function __construct()
{
$config = new Configuration();
$connectionParams = array(
'url' => 'mysql://root:secret#localhost/mydb',
);
$this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
}
Which is the 2nd code example in my 1st link. Tells me " Class 'Doctrine\DBAL\Configuration' not found ". Funny thing is, that IntelliJ can perfectly autocomplete the path (suggests me Configuration when finishing DBAL in the path) but PHP doesn't find it. If i remove the new Configuration PHP just tells me, that it doesn't find the DriverManager...
I installed it correctly via composer though, at least composer tells me it is installed correctly now (Where does composer save the libs?)
You now need to require composers autoload file.
require __DIR__.'/vendor/autoload.php';
use Doctrine\DBAL\Configuration;
class Connection
{
var $connection;
//Constructor
public function __construct()
{
$config = new Configuration();
$connectionParams = array(
'url' => 'mysql://root:secret#localhost/mydb',
);
$this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
}
Please note, depending on your directory structure, the autoload file might be somewhere else, but usually this should work.
Pay attention to the use of namespaces: if the Doctrine namespace for its loader is Doctrine\Common\ClassLoader, you have to put the files inside the Doctrine\Common folder ("Doctrine" with a capital "D").
See the code snippet shown inside the Introduction chapter of the Doctrine DBAL documentations.

How to specify database configuration in CakePHP 2.0.2?

I've just installed CakePHP 2.0.2 for use in a new project. I'm trying to use a database configuration called development but my model doesn't seem to be picking it up.
Based on CakePHP 2's new directory and file name conventions, I've created the following at /app/Model/AppModel.php:
<?php
class AppModel extends Model {
public $useDbConfig = 'development';
}
However, the default home page tells me:
Cake is NOT able to connect to the database.
Yet if I change the configuration name in /app/Config/database.php to default the message changes to a success message, as though it's not picking up my custom AppModel class.
How can I remedy this? As the new CakePHP 2.0 docs say to use the $useDbConfig property as I have done above?
EDIT: Contents of /app/Config/database.php:
class DATABASE_CONFIG {
public $development = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'cakephp_db',
'prefix' => '',
'encoding' => 'utf8',
);
}
Like dhofstet has explained, you still need to have a default config. What I do is add a constructor to the DATABASE_CONFIG class to switch between database configs.
Something like this...
public function __construct()
{
if (DEV_SERVER) {
$this->default = $this->development;
} else {
$this->default = $this->production;
}
}
Your database configuration is very likely correct.
The reason "Cake is NOT able to connect to the database." is shown, is because the script that checks whether it can connect to the database (/lib/Cake/View/Pages/home.ctp) only uses the default database connection for this test. And as there is no such connection, it fails.

Categories