I'm using the google-trends library and installed it with composer
composer update jonasva/google-trends
my composer.json:
{
"require": {
"jonasva/google-trends": "dev-master"
}
}
I included the file start.php in the main folder:
require __DIR__ . '/vendor/autoload.php';
$config = [
'email' => 'myemail#gmail.com',
'password' => 'mypass',
];
$session = (new GoogleSession($config))->authenticate();
$response = (new GoogleTrendsRequest($session))
->setDateRange(new \DateTime('2014-02-01'), new \DateTime()) // date range, if not passed, the past year will be used by default
->setLocation('BE') // For location Belgium
->getTopQueries() // cid (top queries)
->send(); //execute the request
$data = $response->getTermsObjects(); // return an array of GoogleTrendsTerm objects
But I get
Fatal error: Class 'GoogleSession' not found in
Should I include files other than vendor/autoload.php?
The author conveniently didn't mention the fact that the actual fully qualified class name is Jonasva\GoogleTrends\GoogleSession.
use Jonasva\GoogleTrends\GoogleSession; at the top of your file.
Check the source code of the library to figure out such information.
You have to use FQDN. Namespace + Classname
$session = (new Jonasva\GoogleTrends\GoogleSession($config))->authenticate();
Related
I'm writing my own PHP framework built on top of Symfony components as a learning exercise. I followed the tutorial found at http://symfony.com/doc/current/create_framework/index.html to create my framework.
I'd now like to wire up my routes against my controllers using annotations. I currently have the following code to setup the routing:
// Create the route collection
$routes = new RouteCollection();
$routes->add('home', new Route('/{slug}', [
'slug' => '',
'_controller' => 'Controllers\HomeController::index',
]));
// Create a context using the current request
$context = new RequestContext();
$context->fromRequest($request);
// Create the url matcher
$matcher = new UrlMatcher($routes, $context);
// Try to get a matching route for the request
$request->attributes->add($matcher->match($request->getPathInfo()));
I have come across the following class to load the annotations but I'm not sure how to use it:
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php
I'd appreciate it if someone could help.
Thanks
I've finally managed to get this working. First I changed where I included the autoload.php file to the following:
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = require __DIR__ . '/../vendor/autoload.php';
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
Then I changed the routes collection bit (in the question) to:
$reader = new AnnotationReader();
$locator = new FileLocator();
$annotationLoader = new AnnotatedRouteControllerLoader($reader);
$loader = new AnnotationDirectoryLoader($locator, $annotationLoader);
$routes = $loader->load(__DIR__ . '/../Controllers'); // Path to the app's controllers
Here's the code for the AnnotatedRouteControllerLoader:
class AnnotatedRouteControllerLoader extends AnnotationClassLoader {
protected function configureRoute(Route $route, ReflectionClass $class, ReflectionMethod $method, $annot) {
$route->setDefault('_controller', $class->getName() . '::' . $method->getName());
}
}
This has been taken from https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/Routing/AnnotatedRouteControllerLoader.php. You may wish to modify it to support additional annotations.
I hope this helps.
I'm using Slim Framework together with Laravel's Eloquent ORM and this is my code:
User.php
class User extends \Illuminate\Database\Eloquent\Model
{
protected $table = 'accounts';
}
index.php
require_once 'vendor/autoload.php';
// Models
include 'app/models/User.php';
$app = new \Slim\Slim();
// Database information
$settings = array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'photo_mgmt',
'username' => 'root',
'password' => '',
'collation' => 'utf8_general_ci',
'prefix' => '',
'charset' => 'utf8',
);
$container = new Illuminate\Container\Container;
$connFactory = new \Illuminate\Database\Connectors\ConnectionFactory($container);
$conn = $connFactory->make($settings);
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
\Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);
$app->get('/', function () use ($app) {
$users = \User::all();
echo $users->toJson();
});
$app->run();
As you can see in my code, I have to include the User.php file in my index.php. But what if I have multiple models? Can I just include a folder and all models will also be included so that it won't look messy including every model file in my index.
Thank you in advance.
UPDATE:
I'm using this piece of code I saw
foreach (glob("app/models/*.php") as $filename)
{
include $filename;
}
Is there a cleaner looking way?
You can use Composer to automatically include classes from your project. Let's say your composer.json file lives in app. Then you can use the classmap attribute in your composer.json to automatically include all classes in models:
...
"require": {
"php" : ">=5.4.0",
"slim/slim" : "2.*",
"illuminate/database" : "5.0.33",
...
},
"autoload": {
"classmap" : [
"models"
]
}
The classmap tells Composer to map all classes in the specified directory(ies). Then, all you need to do is run composer update to update Composer's list of includes whenever you add a new file to this directory.
Yes, there is a much cleaner way to do this, namely autoloading.
It boils down to the use of spl_autoload_register() and of a custom class loader.
The principle is to mimic the namespace with the file hierarchy and load these accordingly to the namespace:
$loader = function load($class)
{
include __DIR__."/app/$class.php";
}
spl_autoload_register($loader);
$user = new models\User();
This will automatically include the file located at app/models/User.php. It is a good practice to respect uppercases in your namespace; if you namespace is Model\User, the directory should respect the casing (app/Model/User.php)
The problem with your current solution:
foreach (glob("app/models/*.php") as $filename)
{
include $filename;
}
is that it will load all classes, even if the script will not use them. Registering an autoloader will prevent that, only loading the necessary code.
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.
I've got a problem setting up Doctrine with CodeIgniter. When running the following error is coming up:
Fatal error: Class 'Symfony\Component\Console\Helper\HelperSet' not found in /Applications/MAMP/htdocs/CodeIgniter-2.2.1/application/doctrine.php on line 21
The folder structure looks like this
/application/
/application/doctrine.php
/application/libraries/
/application/libraries/Doctrine/
/application/libraries/Doctrine/Common
/application/libraries/Doctrine/DBAL
/application/libraries/Doctrine/ORM
/application/libraries/Doctrine/Symfony
/application/libraries/Doctrine/Doctrine.php
/application/libraries/Doctrine/index.html
This is the line 21
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));
Cannot find out what is the problem..
Followed this tutorial: http://wildlyinaccurate.com/integrating-doctrine-2-with-codeigniter-2/
update This is my doctrine.php in the application folder
<?php
define('APPPATH', dirname(__FILE__) . '/');
define('BASEPATH', APPPATH . '/../system/');
define('ENVIRONMENT', 'development');
chdir(APPPATH);
require __DIR__ . '/libraries/Doctrine.php';
foreach ($GLOBALS as $helperSetCandidate) {
if ($helperSetCandidate instanceof \Symfony\Component\Console\Helper\HelperSet) {
$helperSet = $helperSetCandidate;
break;
}
}
$doctrine = new Doctrine;
$em = $doctrine->em;
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));
\Doctrine\ORM\Tools\Console\ConsoleRunner::run($helperSet);
Just downloaded github version and without any extra settings everything seems to be ok.
Check if the HelperSet.php file exists in Doctrine/Symfony/Component/Console/Helper directory, and add these lines to Doctrine.php in libraries directory (you have to register Symfony classes):
$symfonyClassLoader = new ClassLoader('Symfony', APPPATH.'your_path_to/Doctrine');
$symfonyClassLoader->register();
This GitHub repository is for CodeIgniter 2, don't use it.
Try this tutorial, it works fine for me, even for CI 3.
I am trying to get this phalconphp OAuth2.0 wrapper working on my OAuth2.0 server.
The README of this repository is not very clear on how to use the namespaces.
I have followed the guide but I keep getting the following error :
Fatal error: Class 'Sum\Oauth2\Server\Storage\Pdo\Mysql\Client'
not found in C:\localhost\oauth2-phalcon\public\index.php on line 56
Here is my index.php file :
<?php
require __DIR__."/../vendor/autoload.php";
// Setup IIS Rewrite Rules
// Enable the verbs GET,PUT,POST,DELETE
// Check URL Scan for dissallowed seperators eg ; :
$config = new \Phalcon\Config([
'database' => [
'oauth' => [
'host' => 'localhost\test',
'port' => 1433,
'instance' => 'INSTANCENAME',
'username' => 'test',
'password' => 'test',
'dbname' => 'oauth',
'pdoType' => 'sqlsrv',
'dialectClass' => '\Twm\Db\Dialect\Mssql'
],
],
# ...
]);
# Register The Lib to the loader
$loader = new \Phalcon\Loader();
$loader->registerNamespaces([
"Twm\Db\Adapter\Pdo" => "../app/library/db/adapter/",
"Twm\Db\Dialect" => "../app/library/db/dialect/",
"League" => "../vendor/league/oauth2-server/src/League/OAuth2/Server",
//"Sum\Oauth2\Server\Storage\Pdo" => "../Oauth2/Server/Storage/Pdo/Mysql",
"Sum" => "../Oauth2/Server/Storage/Pdo/Mysql",
//"Sum\Oauth2\Server\Storage\Pdo\Mysql" => "../Oauth2/Server/Storage/Pdo/Mysql "
# ...
])->register();
$app = new \Phalcon\Mvc\Micro();
# set as service
$app->setService('oauth', function() use ($config) {
// HERE! We use our custom MSSQL Adapter
//$oauthdb = new Phalcon\Db\Adapter\Pdo\Mysql($config->database->oauth->toArray());
$oauthdb = new \Twm\Db\Adapter\Pdo\Mssql($config->database->oauth->toArray());
$server = new \League\OAuth2\Server\Authorization(
new \Sum\Oauth2\Server\Storage\Pdo\Mysql\Client($oauthdb),
new Sum\Oauth2\Server\Storage\Pdo\Mysql\Session($oauthdb),
new Sum\Oauth2\Server\Storage\Pdo\Mysql\Scope($oauthdb)
// new \Sum\Oauth2\Server\Client($oauthdb),
//new \Sum\Oauth2\Server\Session($oauthdb),
//new \Sum\Oauth2\Server\Scope($oauthdb)
);
# Not required as it called directly from original code
# $request = new \League\OAuth2\Server\Util\Request();
# add these 2 lines code if you want to use my own Request otherwise comment it
$request = new \Sum\Oauth2\Server\Storage\Pdo\Mysql\Request();
$server->setRequest($request);
$server->setAccessTokenTTL(86400);
$server->addGrantType(new League\OAuth2\Server\Grant\ClientCredentials());
});
$app->get('/hello', function() use($world){
$world = "world";
echo "hello {$world}:)";
});
$app->get('/access', function () use ($app) {
try {
$params = $app->oauth->getParam(array('client_id', 'client_secret'));
echo json_encode(
$app->oauth
->getGrantType('client_credentials')
->completeFlow($params)
);
} catch (\League\OAuth2\Server\Exception\ClientException $e) {
echo $e->getTraceAsString();
} catch (\Exception $e) {
echo $e->getTraceAsString();
}
});
$app->handle();
//echo $app->handle()->getContent();
The project repository for the phalcon wrapper is here :
https://github.com/sumeko/phalcon-oauth2
I have contacted the author already but he is not replying to my emails.
I appreciate any help or advice, thanks.
UPDATE
So I solved my issue. Basically you need to have the standard OAuth2 library installed via composer and the phalconphp OAuth2 wrapper.
That solved it :)
This might be a long shot, but the problem might be with the autoloader that you are explicitly defining. If you use composer's autoload, you don't need to include Sum namespace in Phalcon's loader. Remove all vendor-specific paths from $loader->registerNamespaces() and only use require __DIR__ . "/../vendor/autoload.php" for that.
Also, it's often more convenient use composer's autoloader for your internal things too, e.g.:
{
"require": {
"phpunit/dbunit": "*",
"phpunit/phpunit": "*",
"…": "…"
},
"autoload": {
"psr-0": {
"": "../src"
}
}
}
So I solved my issue. Basically you need to have the standard OAuth2 library installed via composer and the phalconphp OAuth2 wrapper. That solved it :)