I have installed autoload via composer in CodeIgniter and I also tested it if the file autoload.php is included and it's. So, if i have a library called Pager in libraries, then how can I instantiate (load) the Pager class? It's a fresh CodeIgniter installation, version 3.1.2
I set in config this:
$config['composer_autoload'] = TRUE;
I have try the following ways in Welcome controller:
$pager = new libraries\Pager(); //Class 'libraries\Pager' not found
$pager = new \libraries\Pager(); //Class 'libraries\Pager' not found
$pager = new \library\Pager(); // Class 'library\Pager' not found
$pager = new Pager(); // Class 'library\Pager' not found
And here is the Pager class from libraries directory:
class Pager {
function __construct()
{
parent::__construct();
echo __CLASS__;
}
}
Thank you for help!
This is in fact unrelated to CodeIgniter.
You need to tell composer that you have your own PHP classes that aren't among autoloaded files.
In your composer.json add one of these:
{
// ...
"autoload": {
"psr-4": { "MyNamespace\\": "src/library/MyNamespace" },
"files": ["src/some/custom/filepath.php"]
}
}
Then run in console update to update autoload.php with your new config:
$ composer update
Now every time you use a class from MyNamespace such as MyNamespace\MyClass it'll look for file src/library/MyNamespace/MyClass.php.
Also, file src/some/custom/filepath.php is always included automatically so you don't need to include it manually. (I don't know what's your usecase).
See for more info: https://getcomposer.org/doc/04-schema.md#autoload
Do you have added it in autoload.php
$autoload['libraries'] = array(
'pager'
);
Related
I am trying to create a hook extension for Contao.
But Contao doesn't seem to be able to load my class from the namespace, which handles the hook.
This is my file structure:
I have tried changing names and added ".php" to the class, looked up tutorials, but I can't find what I am doing wrong. I am fairly inexperienced in this topic, so I might be missing something obvious.
autoload.php
ClassLoader::addNamespaces(array
(
'Memberlevels',
));
gister PSR-0 namespace
*/
if (class_exists('NamespaceClassLoader')) {
NamespaceClassLoader::add('Memberlevels', 'system/modules/memberlevels/classes');
}
if (class_exists('NamespaceClassLoader')) {
NamespaceClassLoader::addClassMap(array
(
'Memberlevels' => 'system/modules/memberlevels/classes/myClass.php'
));
}
/*
* Register the templates
*/
TemplateLoader::addFiles([
'cookiebar' => 'system/modules/memberlevels/templates',
]);
config.php
$GLOBALS['TL_HOOKS']['outputBackendTemplate'][] = array('Memberlevels\myClass', 'myOutputBackendTemplate');
I get the error message:
Attempted to load class "myClass" from namespace "Memberlevels". Did you forget a "use" statement for another namespace?
You are still using the old Contao 3 way of loading classes. In Contao 4, you should use the autoloading feature of composer. The default composer.json of the most recent Contao versions already include autoloading directives for the src/ folder of your Contao installation:
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
Using that, this is how you create & register a hook in a Contao 4.4 compatible way:
// src/EventListener/OutputBackendTemplateListener.php
namespace App\EventListener;
class OutputBackendTemplateListener
{
public function onOutputBackendTemplate(string $buffer, string $template): string
{
// Do something
return $buffer;
}
}
// app/Resources/contao/config/config.php
$GLOBALS['TL_HOOKS']['outputBackendTemplate'][] = [\App\EventListener\OutputBackendTemplateListener::class, 'onOutputBackendTemplate'];
Starting with Contao 4.8 you can also use annotations to register a hook, eliminating the need to register the hook in app/Resources/contao/config/config.php.
This is the index.php
<?php
include 'library/altorouter.php';
$router = new AltoRouter();
$router->setBasePath('/AltoRouter');
$router->map('GET','/', 'home_controller#index', 'home');
$router->map('GET','/content/[:parent]/?[:child]?', 'content_controller#display_item', 'content');
$match = $router->match();
// not sure if code after this comment is the best way to handle matched routes
list( $controller, $action ) = explode( '#', $match['target'] );
if ( is_callable(array($controller, $action)) ) {
$obj = new $controller();
var_dump($obj);
call_user_func_array(array($obj,$action), array($match['params']));
} else if ($match['target']==''){
echo 'Error: no route was matched';
} else {
echo 'Error: can not call '.$controller.'#'.$action;
}
// content_controller class file is autoloaded
class home_controller {
public function index() {
echo 'hi from home';
}
}
and it works good. The home_controller class is supposed to be the default controller.
Problem is, when I remove the class home_controller
class home_controller {
public function index() {
echo 'hi from home';
}
}
and save it as a seprate file home_controller.php in app/controller directroy it does not work.
I understand that the router is unable to locate the home_controller class hence will not show it's content (if i directly include the file home_controller.php it again works as normal).
My question is, how do you map the home_controller as default, which is in a different directory?
It looks like you're not using composer for installing the package. It's standard way in PHP.
1. Install Composer
Here is manual, depending on your OS
2. Call Composer from Command Line
Go to your root directory of your project, open Command Line and type:
composer require altorouter/altorouter
You'll find the package name altorouter/altorouter in composer.json on Github page of package - here.
3. Add loaded files to your index.php
Now you have installed router package. Next step is adding all composer loaded files to your application. Just replace include 'library/altorouter.php'; with following:
<?php
# index.php
require_once __DIR__ . '/vendor/autoload.php';
4. Load Your Controllers by Composer as well
Last step is tell composer where to find your classes.
Open composer.json and add following section:
{
"autolaod": {
"classmap": ["app"]
}
}
Read more about classmap option in documentation.
To update /vendor/autoload.php with this option, just call from command line:
composer dump-autoload
That should be it. If you come at any troubles, let me know which point.
I'm working on a project and it's getting a little too hard for me...
I explain.
I need to parse PDF files with PHP, to analyse the content of those files. To do that, I use pdfparser.org library.
I firstly tried to include this library as usually, without any result.
After having read all the Internet, since this library requires Composer to be installed (and on my web hosting I can't get Composer installed), I have applied the Composer process on my Windows PC. I got the "vendor" folder with the "autoload.php" file. Fine !!
Then, I have tried to include it properly in CodeIgniter. The solution I chose is :
Creating a file "Pdfparser.php" in application/libraries/
class Pdfparser
{
public function __construct()
{
require_once APPPATH."/third_party/pdfparser.php";
}
}
Then, I add the PdfParser "Composer" application in application/third_party/, and in the /third_party/pdfparser.php I simply put :
if (!defined('pdfparser')) {
define('pdfparser', dirname(__FILE__) . '/');
require(pdfparser . 'pdfparser/autoload.php');
}
Then, I add this library to CodeIgniter /application/config/autoload.php as :
$autoload['libraries'] = array('pagination', 'form_validation','email','upload','pdfparser');
Finally, I call it in my function in application/controllers/Admin.php :
$parser = new Pdfparser();
$pdf = $parser->parseFile(myfile.pdf);
$full_text = $pdf->getText();
(This 4. block of code is directly taken from official Documentation here : http://www.pdfparser.org/documentation, and just adapted).
But now, I break the Internet... I have this error :
PHP Fatal error: Call to undefined method PdfParser::parseFile() in /path/application/controllers/Admin.php on line 3083
After having looked CodeIgniter documentation, I try to add the Composer autoloader to the core... in application/config/autoload.php I put :
$config['composer_autoload'] = APPPATH . "/third_party/pdfparser/autoload.php";
Of course, it doest not work. And I'm lost...
Use composer properly. $config['composer_autoload'] = TRUE; and inside your application folder run composer install smalot/pdfparser . Then inside your controller it should run, if not use Use :)
use Smalot\PdfParser;
class My_controller extends CI_Controller {
}
When using composer, to include a library in your project you do something like that :
composer install smalot/pdfparser
Then, to include the newly installed library, you only need to include the "autoload.php" file provided by composer :
<?php
include 'vendor/autoload.php';
$parser = new Pdfparser();
$pdf = $parser->parseFile(myfile.pdf);
$full_text = $pdf->getText();
var_dump($full_text);
Nothing more.
Replace your code
class Pdfparser
{
public function __construct()
{
require_once APPPATH."/third_party/pdfparser.php";
}
}
with
<?php
require_once APPPATH."/third_party/pdfparser.php";
class Pdfparser
{
public function __construct()
{
}
}
Include outside of your class.
Rather than using autoloading you can load library like this...
$this->load->library('library_name');
Example:
$this->load->library('pdfparser');
Here is my folder structure:
Classes
- CronJobs
- Weather
- WeatherSite.php
I want to load WeatherSite class from my script. Im using composer with autoload:
$loader = include(LIBRARY .'autoload.php');
$loader->add('Classes\Weather',CLASSES .'cronjobs/weather');
$weather = new Classes\Weather\WeatherSite();
Im assuming the above code is adding the namespace and the path that namespace resolves to. But when the page loads I always get this error:
Fatal error: Class 'Classes\Weather\WeatherSite' not found
Here is my WeatherSite.php file:
namespace Classes\Weather;
class WeatherSite {
public function __construct()
{
}
public function findWeatherSites()
{
}
}
What am I doing wrong?
You actually don't need custom autoloader, you can use PSR-4.
Update your autoload section in composer.json:
"autoload": {
"psr-4": {
"Classes\\Weather\\": "Classes/CronJobs/Weather"
}
}
To explain: it's {"Namespace\\\": "directory to be found in"}
Don't forget to run composer dump-autoload to update Composer cache.
Then you can use it like this:
include(LIBRARY .'autoload.php');
$weather = new Classes\Weather\WeatherSite();
So I'm writing a Laravel 4 app and I've setup namespaces. I'm just trying to write some systemwide functionality that I can execute from anywhere mainly to create menus/setup language/currencies etc.
I have directory to global called "library" which has currently a file called Menu.php inside it which looks as follows:
<?php
namespace Library;
use AppName\Model\Menu as MenuModel;
class Menu {
public static function BuildMenu($id = 1) {
//retrieve menu
$menu = MenuModel::GetMenu($id);
//sort content for page
$data = $menu->toArray();
print_r($data);
}
}
I am currently attempting to call the BuildMenu function in the filters.php file with the following:
App::before(function($request)
{
//
View::share('Menu', Library\Menu::BuildMenu());
});
I get a class 'Library\Menu' not found error from laravel. I'm presuming this is something to do with my lack of knowledge of namespaces so any clarity would be appreciated.
Did you add your library path to composer.json ?
if not, just add it to autoload > classmap >> app/library
and run artisan dump-autoload
should be fine.