Simply namespaces in PHP - php

I want to include class Proxy from
./proxy/Proxy.php in ./index.php
require_once 'proxy/Proxy.php';
$proxy = new Proxy();
But next I want to use namespaces so I made:
./proxy/Proxy.php
namespace proxy;
class Proxy
{
[...]
and
./index.php
$proxy = new \proxy\Proxy();
or
$proxy = new proxy\Proxy();
or
use proxy\Proxy;
$proxy = new Proxy();
and I always get:
Fatal error: Uncaught Error: Class 'proxy\Proxy' not found in /var/www/proxy/index.php
What is wrong?

Firstly, if you are going to use namepaces, make them PSR-4 autoloader compliant! Check this link:
http://www.php-fig.org/psr/psr-4/
In other words, I'm asking you to change your namespace to Proxy with a capital.
Secondly, to get autoloading working, you need to register an autoloader. You can do it yourself by checking this out http://php.net/manual/en/function.spl-autoload-register.php, or, the better way is to install Composer (https://getcomposer.org/).
Using Composer then, if you aren't currently using it, run composer init from your site root, which will generate a composer.json.
Inside the Json, add this entry:
"autoload": {
"psr-4": {
"Proxy": "src/"
},
},
That assumes all classes beginning with namespace Proxy go in the src directory.
Since you made changes to the autoloading config, run composer dumpautoload and it will generate fresh classmaps.
Finally, in your scripts, require_once 'vendor/autoload.php and you'll never need require a class again!
require_once 'vendor/autoload.php';
use Proxy\Proxy;
$proxy = new Proxy();
The convention is based on file path and name, so src/Proxy.php is namepace Proxy, class Proxy. src/Something/Else.php would be namespace Proxy\Something with class Else.
Have fun! :-D

Try the following inside your index.php:
include 'proxy/Proxy.php';
use proxy\Proxy;
$proxy = new Proxy();
This file with the class needs to be included in order to be accessible. Just calling its namespace isn't enough.

^^The comment from mega6382I should do the trick.
But I wanted to maybe help you any further in your development, I'd suggest you want to autoload the files when you need them? You can use PHP it's own autoloader for it: "spl_autoload_register!".
I'd also recommend you use some better namespaces, \proxy\Proxy makes no sense at all...

Related

Change namespace class autoload to manual require_once PHP

I want to use namespaces class to manual one without using autoload.php to be included. Because I don't want to use all function the class.
I am using this project https://github.com/codenix-sv/coingecko-api to get it's function in my php function.
In the example of using is like this
use Codenixsv\CoinGeckoApi\CoinGeckoClient;
$client = new CoinGeckoClient();
$data = $client->ping();
But I want to change it to require_once. So I put all src folder in my php folder and create this to call the function
require_once 'libs/Api/CoinGeckoClient.php';
$client = new Codenixsv\CoinGeckoApi\CoinGeckoClient;
$data = $client->simple();
First I got this error when trying to access the page.
Fatal error: Uncaught Error: Class 'GuzzleHttp\Client' not found in
C:\xampp\htdocs\te.st\libs\Api\CoinGeckoClient.php:35
Then I try to remove the line "use GuzzleHttp\Client" in CoinGeckoClient.php file.
And got with this error
Fatal error: Uncaught Error: Class 'Codenixsv\CoinGeckoApi\Client' not
found in C:\xampp\htdocs\te.st\libs\Api\CoinGeckoClient.php:35
Is there any way to just use the "simple" function of coingecko only in my php file.
https://github.com/codenix-sv/coingecko-api/blob/master/src/Api/Simple.php
Here is the way I fix this.
load in composer.json like
{
"require": {
"codenix-sv/coingecko-api": "^1.0",
"guzzlehttp/guzzle": "~6.0"
}
}
then do composer update in command window.
In my php file. make sure
use Codenixsv\CoinGeckoApi\CoinGeckoClient;
is placed in top of file. Then do the rest.
Thanks all
That package is prepared to works with composer.
Composer delivered autoloader, to make you work simplier.
If you remove use GuzzleHttp\Client line from CoinGeckoClient.php, there will be no way to send request to the server.
The best option is include composer autoload in your project file, it means you should:
Create composer.json file for you project
Add required library dependency using command: composer require guzzlehttp/guzzle
Add require library dependency using command: composer require codenix-sv/coingecko-api
Inside your project file add folowing line:
require_once(dirname(__FILE__) . '/vendor/autoload.php');
use Codenixsv\CoinGeckoApi\CoinGeckoClient;
$client = new CoinGeckoClient();
$data = $client->ping();
In other way, that will be necessarily to import all files manually. And of course, you haven't to forget about imports for Guzzle client.

Class Amp non found

I'm new on amphp and i'd like to try this very simple code first.
I downloaded amphp with composer for windows and save all folder created inside my project folder.
composer require amphp/http-client
Then my code is:
<?php
require __DIR__ . './autoload.php';
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Amp\Loop;
$stringa = 'http://www.google.it/';
$request = new Request($stringa, "GET");
$location = $request->getHeader("Location");
var_dump($location);
But I get always 'Fatal error: Uncaught Error: Class 'Amp\Http\Client\Request' not found'
Any suggest?
I use wamp local server with php 7.0
Also ,after, I need to yield all the code...
Here are a few things that look for:
Did the autoload.php get included correctly?
I see there is an unnecessary . before /autoload.php.
Did you use the correct class name with the correct namespace?
Did you run composer require amphp/http-client so that the libraries will be installed?
Do the library's files exist inside the vendor/amphp/http-client directory?
If you're on Windows, use \ in the require statement.
Apart from these, I can't think of why the library won't load. I hope this helps.

Composer (Facebook Ads SDK) setup with CodeIgniter

I have a CodeIgniter application. I've been trying to set it up to work with Facebook ADS SDK ( https://github.com/facebook/facebook-php-ads-sdk ).
I want to use a simple lines in my controller like:
use FacebookAds\Object\CustomAudience;
use FacebookAds\Object\Fields\CustomAudienceFields;
use FacebookAds\Object\Values\CustomAudienceSubtypes;
$audience = new CustomAudience(null, 'act_123123');
I have created composer.json file:
{
"require": {
"facebook/php-ads-sdk": "2.8.*"
}
}
I let it through command
php composer.phar install --no-dev
And everything worked fine. It installed me autoload.php with external facebook folder.
Now when it comes to the part where I need to make it work with CodeIgniter I constantly get errors.
I tried two different approaches:
First was to include it in my index.php Like this:
include_once 'application/vendor/autoload.php';
require_once BASEPATH.'core/CodeIgniter.php';
However I was getting errors for not loading my classes that are in application/core folder (Back_Controller is extending CI_Controller and I am using Back_Controller in my every controller, I also have My_Model and Front_Controller there).
Second aproach:
To use CodeIgniter's feature to use Auto-loader together with Composer. So I changed in the config:
$config['composer_autoload'] = TRUE;
Both approaches returned me the same errors:
"Fatal error: Class 'Back_Controller' not found in /public_html/application/controllers/admin/Shops.php on line 4
Warning: include(): open_basedir restriction in effect.
File(application/errors/html/error_php.php) is not within the allowed
path(s): () in /public_html/system/core/Exceptions.php on line 269"
How can I set it up so Facebook SDK actually works together with CodeIgniter?
Any help will be very appreciated. Thank you.
I am thinking that one of the solutions would be to add "autoload" to composer.json so it loads my core classes but I can't figure out how should it be. I tried:
"autoload": {
"psr-4": {
"Back_Controller\\":"core/"
}
}
Try the following:
Include the main Api file
include APPPATH.'vendor/wherever_your_sdk_is/FacebookAds/Api.php';
Then do the following... as per documentation...
use FacebookAds\Api;
// Initialize a new Session and instanciate an Api object
Api::init($app_id, $app_secret, $access_token);
// The Api object is now available trough singleton
$api = Api::instance();
Figured it out.
I just added "autoload" to composer.json to autoload my core files and now both solutions that I tried before - works.
"autoload": {
"psr-4": {
"":"core/"
}
}

Cannot redeclare class error in Laravel but works fine in native php

I am using Alchemy API for filter out some data. Everything works fine in the native code. But when i used it in my Laravel Controller it throws Cannot redeclare class. My controller,alchemyapi.php and example.php are in the same directory. Here is how i include alchemyapi.php in native code
<?php
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI("MY API KEY"); ?>
But when i include it in the controller it throws my the error. is there something i am missing ?
require_once 'alchemyapi.php';
$alchemyapi = new AlchemyAPI("MY API KEY");
The native code(example.php) works well without any issue. But in laravel controller it throws a error saying Cannot redeclare class AlchemyAPI
in alchemyapi.php line 20
Instead of using require_once use namespace in your alchemyapi.php and then use use for same namespace in your MyController
alchemyapi.php
<?php
namespace App\Http\Controller;
class AlchemyApi {
//your code
}
MyController.php
<?php
namespace App\Http\Controller;
use App\Http\Controller\AlchemyApi;
class MyController {
$alchemy = new AlchemyApi("Your_api_key");
}
OK, so what I think is happening is that alchemyapi.php is somehow already being included by the composer autoloader.
Try this.
Create the directory lib in the root of your project.
Move alchemiapi.php into lib.
Under the "autoload" section in your composer.json add the following code. Make sure the JSON is valid:
"files": [
"lib/alchemyapi.php",
],
Run composer dump-autoload. If it errors, your composer.json is invalid or you haven't put the file in the correct place.
Delete require_once 'alchemyapi.php'; from your controller.
When dealing with composer, this is how you deal with classes in the global namespace. After running composer it scan those directories in app for PSR-4 classes.
I can't be sure but I think that composer is looking for it and you are also manually requiring it. That would explain why PHP thinks you are redeclaring the class.

Class 'AWeberAPI' not found

I got no clue why AWeberAPI is not found. Any help is appreciated.
php code:
require('vendor/autoload.php');
new PHPExcel;
new AWeberAPI;
composer.json:
{
"require": {
"aweber/aweber": "^1.1",
"phpoffice/phpexcel": "^1.8"
}
}
The problem
The module doesn't appear to be properly configured for use/autoloading with composer. They may have just added the composer configuration to allow you to easily install it, but not to use it within the composer autoloader.
The generic convention for it is that AWeberAPI should match the package's PSR-4 autoloader format, which says "look in aweber_api", then it will look for a class named AWeberAPI.php. You can test this behaviour is correct by adding this file:
<?php
// File: vendor/aweber/aweber/aweber_api/AWeberAPI.php
class AWeberAPI {
public function __construct() {
die('yeah, it works now...');
}
}
Then try your script again, the class will exist now.
What can I do?
Well - you could submit a pull request to their repository to fix it, but it looks like it would involve renaming the classes and filenames which would be a breaking change so I probably wouldn't bother.
You can get it to work by requiring the actual source of the API library instead of the composer autoloader in this case:
require_once 'vendor/aweber/aweber/aweber_api/aweber_api.php';

Categories