PHP redeclared class from two different files - php

I have the code below. When I run it I get error:
Fatal error: Cannot redeclare class Google_Account in
/var/www/vhosts/example.com/httpdocs/google-api-php-client
/src/contrib/Google_AnalyticsService.php on line 379
That's because both of the "Google_AdsenseService.php" and "Google_AnalyticsService.php" files have a class named Google_Account. The member variables and functions of Google_Account class are different in that files.
I need to get Adsense and Analytics data in the same time. So I need to use both of the services at once. I couldn't find a way to un-declare classes. How can I use both of the services together?
include_once APP.'Vendor/google-api-php-client/src/Google_Client.php';
$client1 = new Google_Client();
$client1->setApplicationName('aaa');
$client1->setDeveloperKey('1234');
$client1->setRedirectUri('http://example.com/');
include_once APP.'Vendor/google-api-php-client/src/contrib/Google_AdsenseService.php';
$client1->setClientId('2345');
$client1->setClientSecret('4444');
$service1 = new Google_AdsenseService($client1);
// some code that gets data from "$service1"
$client2 = new Google_Client();
$client2->setApplicationName('aaa');
$client2->setDeveloperKey('1234');
$client2->setRedirectUri('http://example.com/');
include_once APP.'Vendor/google-api-php-client/src/contrib/Google_AnalyticsService.php';
$client2->setClientId('4567');
$client2->setClientSecret('5555');
$service2 = new Google_AnalyticsService($client2);
// some code that gets data from "$service2"

You can add different namespaces at the top of each files in contrib directory. For example for Google_AdsenseService.php file add namespace Google\AdsenseService; at the top.
// Google_AdsenseService.php file
namespace Google\AdsenseService;
As long as the file contents are only referencing the contents from same file it'll will work. Only when you access it you access by namespace. Like this,
$service1 = new Google\AdsenseService\Google_AdsenseService($client1);

You have two options:
For PHP 5.3+, you can add a namespace at the start of the file. After this, you need to fix references to other classes from the modified class (Exception will become ::Exception, etc.)
You may rename the class in a text editor, this will be probably easier. Just open up the file in your favorite text editor, and use replace all. Change Google_Client to something else. There is a good change the lib won't use dynamic class construction and other funny stuff, so your quickly refactored code will work.

Related

Declare only once the Use "Namespace" initialization and all files got the same namepace for an object

I got a simple question for you hopefully. Can it be possible that I just initialize the namespace for a class once in my "main file" and all other objects or classes got the same reference of it ?
For example Index.php:
require_once 'init.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
and now I got a class not in the same file with this kind of code. Controller.php:
function programmAction($id) {
$programm = $this->model->getProgrammById($id);
$html = $this->renderTemplate($this->tempProgramm,['programm' => $programm]);
return new Response($html);
}
Normally when I don't add the use lines as well to this file I would get an error message that the class Response was not found.
Only if you include all other classes in the same file. Refer to this note from the manual:
Note:
Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.
Please don't include all of your classes in one file.
It may seem like a pain to retype the use statements in each and every class file, but really it will help you when you go back and refer to that file later. Right at the top is a list of classes that your class depends on, and could be helpful information during a refactoring or code reorganization.

How to attach classes automatically by their name?

I downloaded the PHP Amazon MWS Reports Client Library from here:
https://developer.amazonservices.com/gp/mws/api.html/182-5103998-0984662?ie=UTF8&group=bde&section=reports&version=latest
and I was trying to get it to work but it looks like the library is not complete out of the box or there is something that I don't fully understand. For example in the samples folder there are sample functions that should let you get up to speed in no time however when you run any of them, PHP complains about missing classes. Lets take at one of the top lines of one of them:
$service = new MarketplaceWebService_Client(
'xyz',
'xyz',
$config,
'xyz',
'1.0');
So it is instancing the MarketplaceWebService_Client however that class is neither attached to this file nor nowhere to be found inside of it. After a quick search I found that the function exist under the following hierarchy:
MarketplaceWebService/Client.php
Can you see the resemblance to the class name? How is that supposed to work? Should I add all of those files using require_once or there should be any mechanism that loads them automatically?
Another one: class MarketplaceWebService_Model_GetReportListRequest exist under
MarketplaceWebService/Model/GetReportListRequest.php
I know that I could create an __autoload function and simply attach those classes dynamically but is this what the author had in mind?
PHP has an autoload capability which enables a function to be called if a required class does not exist at runtime. This capability allows the script to go and produce the missing class, normally by including a file which contains it.
Here's an example adapted from the PHP manual.
// Your missing class is called MarketplaceWebService_Client
// The code for this class is in MarketplaceWebService/Client.php
// define a function that will be called when a class does not yet exist
function my_autoloader($class) {
// implement the rules to convert the class into the file naming convention
$path = str_replace('_', '/', $class) . 'php';
// if there is a match, then include it now
if(file_exists($path)) {
include_once $path;
}
}
// tell PHP about the autoload function
spl_autoload_register('my_autoloader');
You may need to tweak the above example to fit your specific code and folder structure.
I can't speak to the PHP client library, but the C# library is complete out of the box and compiles from the start. The MWS team has a dedicated contact us page for these type of issues. They are willing to work with you through your issues and get you moving. You do have to log in with your seller credentials to access this page. Give it a try.
https://sellercentral.amazon.com/gp/mws/contactus.html

How can I call a function in a php class?

This is a sample code:
sample code
I want to call it in another page:
include 'root of class file';
$r = new ImagineResizer();
I got this error:
Fatal error: Class 'ImagineResizer' not found in C:\WampDeveloper\Websites\example.com\webroot\images.php on line 13
Also call the function:
$r->resize('c:/test1.jpg', 'c:/test2.jpg');
As seen in your sample code the class is located in another namespace :
<?php
namespace Acme\MyBundle\Service;
use Symfony\Component\HttpFoundation\File\File;
use Imagine\Image\ImagineInterface;
use Imagine\Image\BoxInterface;
use Imagine\Image\Point;
use Imagine\Image\Box;
class ImagineResizer {
//-- rest of code
}
To use a class in another namespace you need to point out where the file is :
First include the class (manual or with autoloading)
Then u can create an instance in 2 ways. First way with the use-keyword
use Acme\MyBundle\Service\ImageResizer;
$object = new ImageResizer();
Or point to the class absolute :
$object = new \Acme\MyBundle\Service\ImageResizer();
Hopefully, this will help you out some:
Make sure you include the actual file - not just the folder where it lies.
Make sure that the file you're calling the class from uses the same namespace as your class file. If it doesn't, you have to call the class using the full namespace.
Profit.
The namespaces really had my patience go for a spin when I started using them, but once you're used to it it's not too hard. I would recommend using an autoloader though. It's a bit of a hassle to set up, but once it's done it helps out a bunch.
Namespaces: http://php.net/manual/en/language.namespaces.php
Autoloader: http://php.net/manual/en/function.spl-autoload-register.php

Trouble with Namepaces and Class Loading

Im building a custom CMS and have setup an autoloader, and have adapted use of namespaces. For the most part things are loading properly, but in certain cases PHP reports that it cannot find the class, the class file has been included.
Once a file is included (using require), it should be instanced as well.
The parent controller is instanced, then the child controller attempts to instance a few of its own dependencies.
$this->auth = new \Modules\Auth\RT\Auth();
This will look for a file at /modules/auth/rt/auth.php, and it does and the class is instanced properly.
The namespace of Auth is:
namespace Modules\Auth\RT;
The auth class tried to load its own dependencies, a model in particular.
$this->auth_model = new Models\ModelAuth();
Here the file to be included is at /modules/auth/rt/models/modelauth.php
It is included successfully, but this is where PHP says I cannot find this class.
Fatal error: Class 'Modules\Auth\RT\ModelAuth' not found in /Users/richardtestani/Documents/ShopOpen-Master/shopopen/modules/auth/rt/auth.php on line 12
What would cause the class from not being instanced even though the file is included?
Thanks
Rich
try this:
$this->auth_model = new Modules\Auth\RT\Models\ModelAuth();
try this:
$this->auth_model = new \Modules\Auth\RT\Models\ModelAuth();
OR
$this->auth_model = new Models\ModelAuth();
when you are in this namespace \Modules\Auth\RT
There was a Missing \ , so the code trys to include the namespace twice;
FOR REAL ;)

PHP: php can't find a class defined in an include() script

I am trying to use Michelf's PHP implementation of Markdown.
I'm including his Markdown.php script with include() at the beginning of my main script, but when trying to use the class (be it for creating a new object or using a method directly), I get this:
Fatal error: Class 'Markdown' not found in [my main script]
The class Markdown is cleary defined in included Markdown.php however.
I've checked, of course, that the include works. I've tried placing Markdown.php in both my include_path and my main script's path, it doesn't change anything.
I am at a loss.
Judging by the source file, you most likely forgot to import the class before using it:
use Michelf\Markdown;
// ...
$md = new Markdown();
Alternatively, you could use the canonical name:
$md = new \Michelf\Markdown();

Categories