I am trying to register my own class as a services with help of symfony dependency injection component, but i have problems with class loading.
I have file structure as this:
My Generator class is simple
<?php
namespace Localhost\Service\String;
class Generator {
private $iStringLength;
public function __construct($iNewStringLength = 5) {
$this->iStringLength = $iNewStringLength;
}
public function getRandomString() {
$sChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$sRandChar = substr(str_shuffle(str_repeat($sChars,5)),0, $this->iStringLength);
return $sRandChar;
}
}
And Index is
<?php
require_once 'vendor/autoload.php';
/*
spl_autoload_register(function ($sClass) {
echo $sClass;
require_once str_replace('\\', '/', $sClass) . '.php';
});
*/
use Localhost\Service\String\Generator;
/*
$oStringGenerator = new Generator(55);
echo $oStringGenerator->getRandomString();
*/
use Symfony\Component\DependencyInjection\ContainerBuilder;
$oContainer = new ContainerBuilder();
$oContainer
->register('generator', 'Generator')
->addArgument('15');
$oGeneratorService = $oContainer->get('generator');
echo $oGeneratorService->getRandomString();
What i am getting is an error
Fatal error: Uncaught exception 'ReflectionException' with message 'Class Generator does not exist' in D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php:959 Stack trace: #0 D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php(959): ReflectionClass->__construct('Generator') #1 D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php(493): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), 'generator') #2 D:\Localhost\Apache\htdocs\Test\index.php(26): Symfony\Component\DependencyInjection\ContainerBuilder->get('generator') #3 {main} thrown in D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php on line 959
Or as a picture
$oContainer = new ContainerBuilder();
$oContainer
->register('generator', 'Localhost\Service\String\Generator')
->addArgument('15');
Solution is simple, i forgot to modify composer config to load my services
"autoload": {
"psr-0": {"Localhost": "src/"}
},
Edit: Since Symfony 3.3+ (May 2017) you can use register() class name service shortcut:
$containerBuilder = new ContainerBuilder();
$containerBuilder->register(Localhost\Service\String\Generator::class)
->addArgument('15');
Since PHP 5.5+ you can use more fail-proof ::class notation:
$containerBuilder = new ContainerBuilder();
$containerBuilder->register('generator', Localhost\Service\String\Generator::class)
->addArgument('15');
Now, when class name will be miss-typed, your IDE will highlight it.
addition:
You should propbably compile the container for performance reasons.
$container = new ContainerBuilder();
$container
->register('generator', 'Localhost\Service\String\Generator')
->addArgument('15')
;
$container->compile();
Related
I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:
[16-Sep-2022 11:05:02 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
Stack trace:
#0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
#1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
#2 {main}
thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11
I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:
error_reporting(E_ALL ^ E_NOTICE);
define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
define('I', 'interfaces/');
// Management
require_once C . 'config.php';
// Interfaces
require_once A . I . 'interface.engine.php';
require_once A . I . 'interface.core.php';
require_once A . I . 'interface.template.php';
// Classes
require_once A . 'class.engine.php';
require_once A . 'class.core.php';
require_once A . 'class.template.php';
// OBJ
$engine = new Kit\engine();
$core = new Kit\core();
$template = new Kit\template();
// Start
session_start();
$template->Initiate();
This references the class.engine.php first which is where I have created the database connection class, as shown below:
namespace Kit;
use PDO;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class engine
{
public $pdo;
public function __construct()
{
global $_CONFIG;
$dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
} catch (\PDOException $e) {
print "<b>An error has occurred whilst connecting to the database:</b><br />" . $e->getMessage() . "";
die();
}
}
}
$connection = new engine();
I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:
namespace Kit;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class core implements iCore
{
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function website_settings()
{
$qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
$qry->execute([]);
if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
}
}
Sorry if this is a simple fix but I really can't see where I'm going wrong.
Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed
Just guessing, but i think
$core = new Kit\core($engine->pdo);
will fix your issue.
Im using this library https://serp-spider.github.io/documentation/search-engine/google/
When I follow their example I got this.
Fatal error: Uncaught Error: Class "Serps\SearchEngine\Google\GoogleClient" not found in /var/www/html/index.php:19 Stack trace: #0 {main} thrown in /var/www/html/index.php on line 19
This is my index.php
<?php
use Serps\SearchEngine\Google\GoogleClient;
use Serps\SearchEngine\Google\GoogleUrl;
$googleClient = new Serps\SearchEngine\Google\GoogleClient($httpClient);
$googleUrl = new GoogleUrl();
$google->setSearchTerm('simpsons');
$response = $googleClient->query($googleUrl);
$results = $response->getNaturalResults();
foreach($results as $result){
// Here we iterate over the result list
// Each result will have different data based on its type
}
?>
I've been thinking about what it could be for a while but I can't
I was missing the autoload, I added this line and works.
require 'vendor/autoload.php';
I changed the namespace and forgot to update it in composer.json
"autoload": {
"psr-4": {
"MyNamespace\\": "src"
}
},
Then run composer dump-autoload
I am new at Zend2 and i am following the Album tuturial on Zend. I get the following error:
Fatal error: Uncaught Error: Class 'ArrayUtils' not found in E:\Temp\htdocs\zf-tutorial\public\index.php:43 Stack trace: #0 {main} thrown in E:\Temp\htdocs\zf-tutorial\public\index.php on line 43
I can't find whats the problem, what do i do wrong? Do i miss some code? Or do i miss some rules in the tutorial?
here is my index.php file
<?php
use Zend\Mvc\Application;
/**
* Display all errors when APPLICATION_ENV is development.
*/
if ($_SERVER['APPLICATION_ENV'] === 'development') {
error_reporting(E_ALL);
ini_set("display_errors", 1);
}
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
$path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (__FILE__ !== $path && is_file($path)) {
return false;
}
unset($path);
}
// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';
if (! class_exists(Application::class)) {
throw new RuntimeException(
"Unable to load application.\n"
. "- Type `composer install` if you are developing locally.\n"
. "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
. "- Type `docker-compose run zf composer install` if you are using Docker.\n"
);
}
// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/../config/development.config.php')) {
$appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}
// Run the application!
Application::init($appConfig)->run();
To be able to use the Zend\Stdlib\ArrayUtils class, you have to either:
add a use statement at the top of your file: use Zend\Stdlib\ArrayUtils; or
change your ArrayUtils invocation to Zend\Stdlib\ArrayUtils
I am still learning to use php composer
i have a directory structure like this :
Directory Structure
and this is my composer.json
{
"autoload": {
"psr-4": {
"Kct\\": "lib/"
}
}
}
Now in my index.php file i am trying to load Class tes in tesdir.php
<?php
// file: index.php
require __DIR__ . '/vendor/autoload.php';
$x = new \Kct\Tesdir\Tes();
var_dump($x->tes()); //output: 'GET'
my tesdir.php :
<?php
namespace Kct\Tesdir;
class Tes {
public function tes() {
return $_SERVER['REQUEST_METHOD'];
}
}
now if I open index.php in my localhost I got and error like this :
Fatal error: Uncaught Error: Class 'Kct\Tesdir\Tes' not found in /var/www/html/tesComposer/index.php:6 Stack trace: #0 {main} thrown in /var/www/html/tesComposer/index.php on line 6
can someone explain why.?
tesdir.php should be named Tes.php. The name of the file should match the name of the class.
See the PSR-4 examples
This seems like a fairly simple reflection problem, yet I can't figure it our. I use Laravel 4.2 on Debian with PHP 5.6.6-1.
Basicly what happens is that I want to spawn a new object from a class in a Laravel QueueHandler like so:
$className = 'MyClass';
$myobject = new $className ();
and this doesn't work. I tried everything I can possibly think of and have no clue where to look. This code doesn;t work while it should:
<?php
use Pronamic\Twinfield\Secure\Config;
use Pronamic\Twinfield\Customer\CustomerFactory;
class TwinfieldQueueHandler {
private $twinfieldConfig = null;
...
try {
$twinfieldFactoryClass = 'CustomerFactory';
//returns 0
echo strcmp('CustomerFactory', $twinfieldFactoryClass);
//works
$test0 = new CustomerFactory ($this->twinfieldConfig);
//throws an exeption with message: "Class CustomerFactory does not exist"
$r = new ReflectionClass($twinfieldFactoryClass);
$test1 = $r->newInstanceArgs($this->twinfieldConfig);
//gives error PHP Fatal error: Class 'CustomerFactory' not found in {file} on line {line}
$test2 = new $twinfieldFactoryClass ($this->twinfieldConfig);
} catch (Exception $e) {
Log::error($e->getMessage());
}
Has anyone got any pointers on where to look and how to debug this?
ReflectionClass will ignore your current namespace and use statements completely. You have to specify the fully qualified name of the class:
$r = new ReflectionClass('Pronamic\Twinfield\Customer\CustomerFactory');
As a user points out on php.net:
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.
Note that you could work around this by passing an object:
$test0 = new CustomerFactory ($this->twinfieldConfig);
$r = new ReflectionClass($test0);