Creating object for Amazon MWS api class not working in cakephp3 - cakephp-3.0

I have added amazon MWS API files at webroot folder in cakephp3.And I tried to call that api classes inside my controller. But its not working. It showing following error
Fatal error: Class 'App\Controller\MarketplaceWebService_Client' not found
Here is my code within a function
require_once 'MarketplaceWebService/Samples/.config.inc.php';
require_once 'MarketplaceWebService/Model/SubmitFeedRequest.php';
require_once 'MarketplaceWebService/Client.php';
require_once 'MarketplaceWebService/Model/GetFeedSubmissionResultRequest.php';
$accesskey=AWS_ACCESS_KEY_ID;
$secretkey=AWS_SECRET_ACCESS_KEY;
$serviceUrl = "https://mws.amazonservices.com";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebService_Client($accesskey,$secretkey,$config,APPLICATION_NAME,APPLICATION_VERSION);
Please help me to fix this issue.
Thank you

new MarketplaceWebService_Client will try to locate that class in your current namespace. You presumably want new \MarketplaceWebService_Client instead (or something along those lines, depending on whether or not it's defined in a namespace in the implementation).
You probably also want to read up on namespaces, composer and autoloading, as all of your require_once calls can probably be eliminated with suitable updates to your environment.

Related

namespace and require_once amazonpay

i am trying to use amazonpay and encounter the following problem;
when i if ($whatever) require_once("amazonpay_stuff.php") with content:
namespace AmazonPay
require_once "apay/config.php";
include 'apay/amazon-pay.phar';
and then in the same file where i have the require i try to use
$client = new Client($amazonpay_config);
this does not work and i get error message
Fatal error: Class 'Client' not found in ....
when i have all that code in one file;
namespace AmazonPay
require_once "apay/config.php";
include 'apay/amazon-pay.phar';
$client = new Client($amazonpay_config);
it works fine - how can i make it work with require_once?

CakePHP static name of controller

I'm probably missing something really obvious here, but is there a function in CakePHP (I'm on 3.8) that returns the name of a controller without creating an instance of the class?
An instanced controller can call this function:
echo $this->name;
But what I'd like to be able to do, is avoid typing the controller name as a string in, say, an HTML->link(); ie a static call something like:
echo $this->Html->link(
'Dashboard',
['controller' => DashboardsController::name, 'action' => 'index']
);
The reason is that I'm refactoring a couple of controllers and am having to find and replace all of those strings by hand. I come from a .Net background and CakePHP is pretty new to me, so if there's a better (more cakeish) way to carry out the refactoring than the question I'm asking, then I'd be really glad to hear it.
Nothing in the documents is leaping out at me, but I've a feeling there should be a simple answer.
The namespace of a class can be retrieved using ::class property. Checkout the following example:
DashboardsController::class // Cake/Controllers/DashboardController
The name without the namespace can be retrieved with ReflectionClass:
$function = new \ReflectionClass(DashboardsController::class);
var_dump($function->inNamespace());
var_dump($function->getShortName());
Shortname can be used to get the class without namespace:
namespace App;
class Test {
public static function name(){
$function = new \ReflectionClass(self::class);
return $function->getShortName();
}
}
var_dump(Test::name());
Checkout the docs: https://www.php.net/manual/en/language.oop5.constants.php#example-186
Reflection: https://www.php.net/manual/en/reflectionclass.getname.php

PHP namespace behaviour gives FATAL error with spl_autoload_register

I want to use namespace and spl_autoload_register together but failed with different error each time.
Please See complete code files on github.
Below are the files
a base file where create a class with namespace class.alpha.php
an include file where I define spl_autoload_register include.php
an example file which instantiate the class object eg.php
Now when I create object from eg.php it gives FATAL error but when I comment namespace line in class.alpha.php then it's working
Please see the code below.
alpha.class.php
<?php
//namespace Alpha; //<< comment and uncomment this to regenerate the error
class Alpha
{
// public static $baseDir_;
public $dir = __DIR__;
public static $baseDir_;
public function __construct()
{
echo __FILE__."=>".__METHOD__;
var_dump(self::$baseDir_, $this->dir);
$firstDir = !empty(self::$baseDir_) ? self::$baseDir_ : $this->dir;
}
}
include.php
<?php //namespace Alpha\config;
spl_autoload_extensions(".php");
spl_autoload_register('loadclass');
function loadclass($class)
{
try {
if (is_readable(strtolower($class).".class.php")) {
include_once strtolower($class).".class.php";
}
} catch (Exception $e) {
print "Exception:". $e;
}
}
//#link http://php.net/manual/en/function.spl-autoload-register.php
// spl_autoload_register(__NAMESPACE__.'Alpha\Alpha()' );
eg.php
<?php
require_once 'include.php';
/** below code works by commenting 1st line on alpha.class.php
if we un comment then below code gives Fatal error: Class 'Alpha' not found */
Alpha::$baseDir_ = '/opt/lampp/archive/';
$obj_ = new Alpha();
var_dump(get_included_files());
var_dump($obj_);
/** now we define namespace Alpha on alpha.class.php */
// $ns_ = new Alpha\Alpha(); // Fatal error: Class 'Alpha\Alpha' not found
// var_dump($ns_);
/** not working even with use statement */
// use Alpha;
// use Alpha;
// $fn = new Alpha\Alpha();
// var_dump($fn);
Please help me out to solve this issue.
Thanks
Your autoloader is receiving a request for a class of "Alpha\Alpha" if you uncomment the namespace in alpha.class.php and place the use Alpha\Alpha in eg. This means that the location it's expecting to find your class in would be alpha\alpha.class.php.
Unless you're on Windows, directory separators are typically forward slash (/). So there's a number of possible solutions.
**Possible Solution #1 - Leave all files in the same place **
If you want to leave everything where it is now, you'll need to remove the namespace from the class names in the autoloader. If you add these lines to the top of your autoloader, that will make it behave that way:
$classParts = explode("\\", $class);
$class = $classParts[count($classParts) - 1];
I would not recommend this solution though since it means that you can no longer provide the same class name in a different namespace.
Possible Solution #2 - Put namespaces in subdirectories
For this solution, you'd create a new directory "alpha" and move "alpha.class.php" into it. For autoloader changes, you can add the following lines to the top of your autoloader:
$class = str_replace("\\", "/", $class);
This will change the namespace separators from backslashes to file path separators with forward slash. This will work on windows as well as mac and linux.
Possible Solution #3 - Follow an established autoloading standard
There are already a number of standard PHP autoloading standards. PSR-0 (now deprecated) works, but PSR-4 would be recommended:
PSR-0: http://www.php-fig.org/psr/psr-0/
PSR-4: http://www.php-fig.org/psr/psr-4/
One big upside of following one of these standards is that there are already plenty of implementations for them and there's been a lot of thought put into how they should work and maintain compatibility with other libraries you may end up wanting to use. Composer (http://getcomposer.org) will allow you to set up and use both PSR-0 and PSR-4 style autoloaders based on a very simple configuration.
Anyway, for the TL;DR crowd, the issue is that the autoloader receives the entire namespaced path in order to know how to load the class. The fatal error was because the autoloader wasn't properly mapping from that namespaced class to a file system location, so the file containing the class was never being loaded.
Hope this helps.

Laravel 3: Class not found in namespace

This is the problem: I haven't be able to load a class from a namespace.
I'm developing a restful app and I'm trying to follow the Entity/Service/Repository way to access and give format to the requested data. The thing is that I cannot load any class from Services. I have created a folder inside my app called api, and within it the others 3 folders: api/entities/, api/services/ and api/repositories/. There are 2 more folders inside services: validators and datapickers.
As it is a RESTulf app, I also created an api folder inside the controllers folde: controllers/api/.
Here is the the current tree of my app folder:
app/
api/
entities/
repositories/
services/
datapickers/
MemberData.php
ConsumeData.php
validators/
...
models/
controllers/
api/
members.php
(other restful controllers)
languages/
...
In first instance, this is my Autoload section from start.php:
Autoloader::directories(array(
path('app').'models',
path('app').'libraries',
path('app').'api'
));
Autoloader::namespaces(array(
'Api' => path('app').'api',
));
And this is MemberData.php:
<?php
namespace Api\Services\Datapickers;
use Api\Repositories as Repo;
class MemberData
{
/* Do some stuff */
}
Now, when I try to use MemberData in controllers/api/members.php:
<?php
use Api\Services\Datapickers\MemberData;
class Api_Members_Controller extends Api_Base_Controller
{
public function get_index($id = null)
{
if (!empty($id))
$this->params->data = MemberData::getById($id);
else
{
$this->params->data = MemberData::getAll(
Input::get('offset'),
Input::get('limit')
);
}
return Response::json($this->params, 200);
}
}
I get the following:
Unhandled Exception
Message:
Class 'Api\Services\Datapickers\MemberData' not found
Location:
/path_to_project/application/controllers/api/members.php on line 15
which is this line: $this->params->data = MemberData::getById($id);
I autoload the api folder and register the base api namespace in start.php but I still keep receiving the same error. IT's like Laravel doesn't recognize the api namespace or something like that.
I tried to register the full namespace:
Autoloader::namespaces(array(
'Api\Services\Datapickers' => path('app').'api/services/datapickers',
));
but the error I got was: Call to undefinde method 'Api\Services\Datapickers\MemberData::getById()'. This was just a test (I don't want to register every sub-namespace in the Autoloader).

Shared Functions in CI2: Helper? Library?

I'm still quite new to OOP, and have been learning-as-I-go with CodeIgniter2+Doctrine2.
I have a couple of shared functions that are handy in various areas of my project, so I'd like to call them. In procedural PHP I'd just stick them in a library file and call them. But that's not working for me now..
include 'function_library.php';
$name = $this -> function_library -> generate_male_name();
Message: Undefined property: Turn::$function_library
I even read somewhere that you needed to use call_function(), but that only got me:
Fatal error: Call to undefined method Turn::call_function()
So I figured maybe I should load it as a helper.
$this->load->helper('character_helper');
echo generate_male_name();
Fatal error: Using $this when not in object context in
/PATH/systemFolder/helpers/character_helper.php
on line 19
Line 19:
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Malenames u");
I considered setting it up as a Library, but honestly that begins to get a little over my head in terms of Classes and such. I have not tried it.
Here is the entirety of that function:
function generate_male_name() {
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Malenames u");
$result = $query->getSingleResult();
//echo $result2[1];
$highval = $result[1];
$random_name = rand(1,$highval);
//echo $random_name;
$name = $this->doctrine->em->find('ORM\Dynasties2\Malenames', $random_name);
return $name->getName();
}
How can I do this?
Edit:
Tried a few additional things, still no success.
I put my function_library in third_party, and did:
$this->load->add_package_path(APPPATH.'third_party/function_library/');
$name = $this -> generate_male_name();
Fatal error: Call to undefined method Turn::generate_male_name()
or $name = $this -> function_library -> generate_male_name();
Message: Undefined property: Turn::$function_library
I'm not crazy about calling it in autoloader, I don't need it everywhere, and that seems less than efficient.
I've read up on libraries, but as I said, Classes are quickly over my head and creating a new library seems more than a little daunting to me.
*What's the best solution here? How do I share a few functions? Is a library the way I need to go, or am I just missing something minor in trying to make a helper or shared_functions thing work?*
May be not an answer, only talking about CodeIgniter
Fatal error: Using $this when not in object context in
/PATH/systemFolder/helpers/character_helper.php on line 19
This happens when you try to use CI instance with $this keyword outside of object context (when CI is not instantiated). Observing the error above I can guess that you are using $this inside the helper character_helper.php that is located inside the helpers folder but outside of CI object context. To use CI object you must instantiate the CI using
$ci = & get_instance();
and use $ci instead of $this in your helper.
If you want to use your helper inside any controller then you can load it normally inside your controller as usual, i.e.
$this->load->helper('character_helper');
and if your helper has a function generate_male_name then you can call it inside your controller as follows
generate_male_name();
$this, however, only works directly within your controllers, your
models, or your views.
Creating CodeIgniter Libraries.