PHP : set client base URL with singleton - php

So, I want to create a client base URL with singleton.
This is my GuzzleClient.php which is containing the base URL
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class GuzzleClient {
public static function getClient()
{
static $client = null;
if (null === $client)
{
$client = new Client([
'base_url' => 'http://localhost:8080/task_manager/v1/',
]);
}
return $client;
}
private function __construct()
{}
}
And this one is where I should put the base url
require_once 'GuzzleClient.php';
class CardTypeAPIAccessor
{
private $client;
public function __construct($client)
{
$this->client = $client;
}
public function getCardTypes() {
$cardTypes = array();
try
{
//this is where base URL should be
$response = $client->get('admin/card/type',
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
foreach ($error['types'] as $type)
{
$cardType = new CardType();
$cardType->setId($type['card_type_id']);
$cardType->setCategory($type['category']);
array_push($cardTypes, $cardType);
}
}
}
}
}
I stuck with how to put the method in GuzzleClient into this code.
Thanks

I'm creating an abstract class for my webservices that send requests. The instance of guzzle is created in a singleton file:
use Guzzle\Http\Client;
class GuzzleSingleton
{
private static $_instance = null;
private static $baseUrl = '';
public static function getBaseUrl(): string
{
return self::$baseUrl;
}
private static function setBaseUrl($baseUrl): void
{
self::$baseUrl = $baseUrl;
}
public static function getInstance(string $apiUrl, ?int $apiPort, string $apiSuffix): ?Client
{
if (is_null(self::$_instance)) {
self::buildApiUrl($apiUrl, $apiPort, $apiSuffix);
self::$_instance = new Client(self::getBaseUrl());
} else {
self::buildApiUrl($apiUrl, $apiPort, $apiSuffix);
self::$_instance->setBaseUrl(self::getBaseUrl());
}
return self::$_instance;
}
private static function buildApiUrl(string $apiUrl, ?int $apiPort, string $apiSuffix): void
{
$apiDns = rtrim($apiUrl, '/');
$urlApi = (!is_null($apiPort)) ? sprintf('%s:%d', $apiDns, $apiPort) : $apiUrl;
$urlApi .= $apiSuffix;
self::setBaseUrl($urlApi);
}
}
My abstract class:
abstract class AbstractWebservice
{
public function __construct(string $apiUrl, ?int $apiPort, ?string $apiSuffixUrl, Session $session)
{
$this->setApiUrl($apiUrl);
$this->setApiPort($apiPort);
$this->setApiSuffixUrl($apiSuffixUrl);
$this->session = $session;
$this->buildFactory();
}
public function buildFactory(): void
{
$this->guzzleWs = GuzzleSingleton::getInstance($this->getApiUrl(), $this->getApiPort(), $this->getApiSuffixUrl());
}
public function sendRequest(string $endpoint, ?array $body, ?array $options, string $method)
{
$request = $this->guzzleWs->createRequest($method, $endPoint, self::$headers, $body, $options);
return $request->send();
}
}

inharit GuzzleClient class into CardTypeAPIAccessor, and check if $client is notinstanceof GuzzleClient then assign access object into $this->client
class CardTypeAPIAccessor extends GuzzleClient
{
private $client;
public function __construct($client)
{
if($client instanceof GuzzleClient){
$this->client = $client
}else{
$this->client = parent::getClient();
}
}
}

Related

How to create statics methods nested a class PHP [duplicate]

Is it possible to chain static methods together using a static class? Say I wanted to do something like this:
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
. . . and obviously I would want $value to be assigned the number 14. Is this possible?
Update: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:
class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return self;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return self;
}
public static function result() {
return self::$value;
}
}
After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).
I like the solution provided by Camilo above, essentially since all you're doing is altering the value of a static member, and since you do want chaining (even though it's only syntatic sugar), then instantiating TestClass is probably the best way to go.
I'd suggest a Singleton pattern if you want to restrict instantiation of the class:
class TestClass
{
public static $currentValue;
private static $_instance = null;
private function __construct () { }
public static function getInstance ()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public function toValue($value) {
self::$currentValue = $value;
return $this;
}
public function add($value) {
self::$currentValue = self::$currentValue + $value;
return $this;
}
public function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return $this;
}
public function result() {
return self::$currentValue;
}
}
// Example Usage:
$result = TestClass::getInstance ()
->toValue(5)
->add(3)
->subtract(2)
->add(8)
->result();
class oop{
public static $val;
public static function add($var){
static::$val+=$var;
return new static;
}
public static function sub($var){
static::$val-=$var;
return new static;
}
public static function out(){
return static::$val;
}
public static function init($var){
static::$val=$var;
return new static;
}
}
echo oop::init(5)->add(2)->out();
Little crazy code on php5.3... just for fun.
namespace chaining;
class chain
{
static public function one()
{return get_called_class();}
static public function two()
{return get_called_class();}
}
${${${${chain::one()} = chain::two()}::one()}::two()}::one();
With php7 you will be able to use desired syntax because of new Uniform Variable Syntax
<?php
abstract class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
return __CLASS__;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return __CLASS__;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return __CLASS__;
}
public static function result() {
return self::$currentValue;
}
}
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
echo $value;
Demo
If toValue(x) returns an object, you could do like this:
$value = TestClass::toValue(5)->add(3)->substract(2)->add(8);
Providing that toValue returns a new instance of the object, and each next method mutates it, returning an instance of $this.
This is more accurate, easier, and read-friendly (allows code-completion)
class Calculator
{
public static $value = 0;
protected static $onlyInstance;
protected function __construct ()
{
// disable creation of public instances
}
protected static function getself()
{
if (static::$onlyInstance === null)
{
static::$onlyInstance = new Calculator;
}
return static::$onlyInstance;
}
/**
* add to value
* #param numeric $num
* #return \Calculator
*/
public static function add($num)
{
static::$value += $num;
return static::getself();
}
/**
* substruct
* #param string $num
* #return \Calculator
*/
public static function subtract($num)
{
static::$value -= $num;
return static::getself();
}
/**
* multiple by
* #param string $num
* #return \Calculator
*/
public static function multiple($num)
{
static::$value *= $num;
return static::getself();
}
/**
* devide by
* #param string $num
* #return \Calculator
*/
public static function devide($num)
{
static::$value /= $num;
return static::getself();
}
public static function result()
{
return static::$value;
}
}
Example:
echo Calculator::add(5)
->subtract(2)
->multiple(2.1)
->devide(10)
->result();
result: 0.63
People are overcomplicating this like crazy.
Check this out:
class OopClass
{
public $first;
public $second;
public $third;
public static function make($first)
{
return new OopClass($first);
}
public function __construct($first)
{
$this->first = $first;
}
public function second($second)
{
$this->second = $second;
return $this;
}
public function third($third)
{
$this->third = $third;
return $this;
}
}
Usage:
OopClass::make('Hello')->second('To')->third('World');
You could always use the First method as a static and the remaining as instance methods:
$value = Math::toValue(5)->add(3)->subtract(2)->add(8)->result();
Or better yet:
$value = Math::eval(Math::value(5)->add(3)->subtract(2)->add(8));
class Math {
public $operation;
public $operationValue;
public $args;
public $allOperations = array();
public function __construct($aOperation, $aValue, $theArgs)
{
$this->operation = $aOperation;
$this->operationValue = $aValue;
$this->args = $theArgs;
}
public static function eval($math) {
if(strcasecmp(get_class($math), "Math") == 0){
$newValue = $math->operationValue;
foreach ($math->allOperations as $operationKey=>$currentOperation) {
switch($currentOperation->operation){
case "add":
$newvalue = $currentOperation->operationValue + $currentOperation->args;
break;
case "subtract":
$newvalue = $currentOperation->operationValue - $currentOperation->args;
break;
}
}
return $newValue;
}
return null;
}
public function add($number){
$math = new Math("add", null, $number);
$this->allOperations[count($this->allOperations)] &= $math;
return $this;
}
public function subtract($number){
$math = new Math("subtract", null, $number);
$this->allOperations[count($this->allOperations)] &= $math;
return $this;
}
public static function value($number){
return new Math("value", $number, null);
}
}
Just an FYI.. I wrote this off the top of my head (right here on the site). So, it may not run, but that is the idea. I could have also did a recursive method call to eval, but I thought this may be simpler. Please let me know if you would like me to elaborate or provide any other help.
Technically you can call a static method on an instance like $object::method() in PHP 7+, so returning a new instance should work as a replacement for return self. And indeed it works.
final class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
return new static();
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return new static();
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return new static();
}
public static function result() {
return self::$currentValue;
}
}
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
var_dump($value);
Outputs int(14).
This about same as returning __CLASS__ as used in other answer. I rather hope no-one ever decides to actually use these forms of API, but you asked for it.
In a nutshell... no. :) The resolution operator (::) would work for the TetsClass::toValue(5) part, but everything after that will just give a syntax error.
Once namespaces are implemented in 5.3, you can have "chained" :: operators, but all that'll do is drill down through the namespace tree; it won't be possible to have methods in the middle of things like this.
The best that can be done
class S
{
public static function __callStatic($name,$args)
{
echo 'called S::'.$name . '( )<p>';
return '_t';
}
}
$_t='S';
${${S::X()}::F()}::C();
No, this won't work. The :: operator needs to evaluate back to a class, so after the TestClass::toValue(5) evaluates, the ::add(3) method would only be able to evaluate on the answer of the last one.
So if toValue(5) returned the integer 5, you would basically be calling int(5)::add(3) which obviously is an error.
The most easiest way i have ever found for method chaining from new Instance or Static method of class is as below. I have used Late Static Binding here and i really loved this solution.
I have created a utility to send multiple User Notification on next page using tostr in Laravel.
<?php
namespace App\Utils;
use Session;
use Illuminate\Support\HtmlString;
class Toaster
{
private static $options = [
"closeButton" => false,
"debug" => false,
"newestOnTop" => false,
"progressBar" => false,
"positionClass" => "toast-top-right",
"preventDuplicates" => false,
"onclick" => null,
"showDuration" => "3000",
"hideDuration" => "1000",
"timeOut" => "5000",
"extendedTimeOut" => "1000",
"showEasing" => "swing",
"hideEasing" => "linear",
"showMethod" => "fadeIn",
"hideMethod" => "fadeOut"
];
private static $toastType = "success";
private static $instance;
private static $title;
private static $message;
private static $toastTypes = ["success", "info", "warning", "error"];
public function __construct($options = [])
{
self::$options = array_merge(self::$options, $options);
}
public static function setOptions(array $options = [])
{
self::$options = array_merge(self::$options, $options);
return self::getInstance();
}
public static function setOption($option, $value)
{
self::$options[$option] = $value;
return self::getInstance();
}
private static function getInstance()
{
if(empty(self::$instance) || self::$instance === null)
{
self::setInstance();
}
return self::$instance;
}
private static function setInstance()
{
self::$instance = new static();
}
public static function __callStatic($method, $args)
{
if(in_array($method, self::$toastTypes))
{
self::$toastType = $method;
return self::getInstance()->initToast($method, $args);
}
throw new \Exception("Ohh my god. That toast doesn't exists.");
}
public function __call($method, $args)
{
return self::__callStatic($method, $args);
}
private function initToast($method, $params=[])
{
if(count($params)==2)
{
self::$title = $params[0];
self::$message = $params[1];
}
elseif(count($params)==1)
{
self::$title = ucfirst($method);
self::$message = $params[0];
}
$toasters = [];
if(Session::has('toasters'))
{
$toasters = Session::get('toasters');
}
$toast = [
"options" => self::$options,
"type" => self::$toastType,
"title" => self::$title,
"message" => self::$message
];
$toasters[] = $toast;
Session::forget('toasters');
Session::put('toasters', $toasters);
return $this;
}
public static function renderToasters()
{
$toasters = Session::get('toasters');
$string = '';
if(!empty($toasters))
{
$string .= '<script type="application/javascript">';
$string .= "$(function() {\n";
foreach ($toasters as $toast)
{
$string .= "\n toastr.options = " . json_encode($toast['options'], JSON_PRETTY_PRINT) . ";";
$string .= "\n toastr['{$toast['type']}']('{$toast['message']}', '{$toast['title']}');";
}
$string .= "\n});";
$string .= '</script>';
}
Session::forget('toasters');
return new HtmlString($string);
}
}
This will work as below.
Toaster::success("Success Message", "Success Title")
->setOption('showDuration', 5000)
->warning("Warning Message", "Warning Title")
->error("Error Message");
Fully functional example of method chaining with static attributes:
<?php
class Response
{
static protected $headers = [];
static protected $http_code = 200;
static protected $http_code_msg = '';
static protected $instance = NULL;
protected function __construct() { }
static function getInstance(){
if(static::$instance == NULL){
static::$instance = new static();
}
return static::$instance;
}
public function addHeaders(array $headers)
{
static::$headers = $headers;
return static::getInstance();
}
public function addHeader(string $header)
{
static::$headers[] = $header;
return static::getInstance();
}
public function code(int $http_code, string $msg = NULL)
{
static::$http_code_msg = $msg;
static::$http_code = $http_code;
return static::getInstance();
}
public function send($data, int $http_code = NULL){
$http_code = $http_code != NULL ? $http_code : static::$http_code;
if ($http_code != NULL)
header(trim("HTTP/1.0 ".$http_code.' '.static::$http_code_msg));
if (is_array($data) || is_object($data))
$data = json_encode($data);
echo $data;
exit();
}
function sendError(string $msg_error, int $http_code = null){
$this->send(['error' => $msg_error], $http_code);
}
}
Example of use:
Response::getInstance()->code(400)->sendError("Lacks id in request");
Here's another way without going through a getInstance method (tested on PHP 7.x):
class TestClass
{
private $result = 0;
public function __call($method, $args)
{
return $this->call($method, $args);
}
public static function __callStatic($method, $args)
{
return (new static())->call($method, $args);
}
private function call($method, $args)
{
if (! method_exists($this , '_' . $method)) {
throw new Exception('Call undefined method ' . $method);
}
return $this->{'_' . $method}(...$args);
}
private function _add($num)
{
$this->result += $num;
return $this;
}
private function _subtract($num)
{
$this->result -= $num;
return $this;
}
public function result()
{
return $this->result;
}
}
The class can be used as following:
$res1 = TestClass::add(5)
->add(3)
->subtract(2)
->add(8)
->result();
echo $res1 . PHP_EOL; // 14
$res2 = TestClass::subtract(1)->add(10)->result();
echo $res2 . PHP_EOL; // 9
Also works as:
ExampleClass::withBanners()->withoutTranslations()->collection($values)
Using new static(self::class);
public static function withoutTranslations(): self
{
self::$withoutTranslations = true;
return new static(self::class);
}
public static function withBanners(): self
{
return new static(self::class);
}
public static function collection(values): self
{
return $values;
}
Use PHP 7! If your web provider cannot --> change provider! Don't lock in past.
final class TestClass {
public static $currentValue;
public static function toValue($value) {
self::$currentValue = $value;
return __CLASS__;
}
public static function add($value) {
self::$currentValue = self::$currentValue + $value;
return __CLASS__;
}
public static function subtract($value) {
self::$currentValue = self::$currentValue - $value;
return __CLASS__;
}
public static function result() {
return self::$currentValue;
}
}
And very simple use:
$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
var_dump($value);
Return (or throw error):
int(14)
completed contract.
Rule one: most evolved and maintainable is always better.

Fatal error: Uncaught Error: Non-static method primaryKey() cannot be called statically [duplicate]

This question already has answers here:
Error message Strict standards: Non-static method should not be called statically in php
(7 answers)
Closed 1 year ago.
how can I fix this error?
Fatal error: Uncaught Error: Non-static method thecodeholic\phpmvc\db\DbModel::primaryKey() cannot be called statically in C:\xampp\htdocs\php-mvc-framework-master\vendor\thecodeholic\php-mvc-core\Application.php:53 Stack trace: #0 C:\xampp\htdocs\php-mvc-framework-master\public\index.php(25): thecodeholic\phpmvc\Application->__construct('C:\\xampp\\htdocs...', Array) #1 {main} thrown in C:\xampp\htdocs\php-mvc-framework-master\vendor\thecodeholic\php-mvc-core\Application.php on line 53
here is my index.php in public folder:
<?php
/**
* User: TheCodeholic
* Date: 7/7/2020
* Time: 9:57 AM
*/
use app\controllers\AboutController;
use app\controllers\SiteController;
use thecodeholic\phpmvc\Application;
require_once __DIR__ . '/../vendor/autoload.php';
$dotenv = \Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();
$config = [
'userClass' => \app\models\User::class,
'db' => [
'dsn' => $_ENV['DB_DSN'],
'user' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD'],
]
];
$app = new Application(dirname(__DIR__), $config);
$app->on(Application::EVENT_BEFORE_REQUEST, function(){
echo "Before request from second installation";
});
$app->router->get('/', [SiteController::class, 'home']);
...
$app->run();
and here is Application.php code:
<?php
/**
* User: TheCodeholic
* Date: 7/7/2020
* Time: 9:57 AM
*/
namespace thecodeholic\phpmvc;
use thecodeholic\phpmvc\db\Database;
/**
* Class Application
*
* #author Zura Sekhniashvili <zurasekhniashvili#gmail.com>
* #package app
*/
class Application
{
const EVENT_BEFORE_REQUEST = 'beforeRequest';
const EVENT_AFTER_REQUEST = 'afterRequest';
protected array $eventListeners = [];
public static Application $app;
public static string $ROOT_DIR;
public string $userClass;
public string $layout = 'main';
public Router $router;
public Request $request;
public Response $response;
public ?Controller $controller = null;
public Database $db;
public Session $session;
public View $view;
public ?UserModel $user;
public function __construct($rootDir, $config)
{
$this->user = null;
$this->userClass = $config['userClass'];
self::$ROOT_DIR = $rootDir;
self::$app = $this;
$this->request = new Request();
$this->response = new Response();
$this->router = new Router($this->request, $this->response);
$this->db = new Database($config['db']);
$this->session = new Session();
$this->view = new View();
$userId = Application::$app->session->get('user');
if ($userId) {
$key = $this->userClass::primaryKey();
$this->user = $this->userClass::findOne([$key => $userId]);
}
}
public static function isGuest()
{
return !self::$app->user;
}
public function login(UserModel $user)
{
$this->user = $user;
$primaryKey = $user->primaryKey();
$value = $user->{$primaryKey};
Application::$app->session->set('user', $value);
return true;
}
public function logout()
{
$this->user = null;
self::$app->session->remove('user');
}
public function run()
{
$this->triggerEvent(self::EVENT_BEFORE_REQUEST);
try {
echo $this->router->resolve();
} catch (\Exception $e) {
echo $this->router->renderView('_error', [
'exception' => $e,
]);
}
}
public function triggerEvent($eventName)
{
$callbacks = $this->eventListeners[$eventName] ?? [];
foreach ($callbacks as $callback) {
call_user_func($callback);
}
}
public function on($eventName, $callback)
{
$this->eventListeners[$eventName][] = $callback;
}
}
$key = $this->userClass->primaryKey();
$this->user = $this->userClass->findOne([$key => $userId]);
i think the function primaryKey and findOne will be normal public and not static in your Entity.
class UserClass {
public function primaryKey() {
....
}
public function findOne() {
...
}
}
so you has to use -> instead of :: to call the methods

Method Chaining in CodeIgniter Library

I've been working on a script for work. It's to use Slack with PHP. At work we use CodeIgniter (sad face) so I have to accommodate and I decided to write my script as a Library.
There isn't an issue here in that the code doesn't work, as it works fine, but I am just interested to know how I can apply method chaining when calling the library so myself and my colleagues can code cleaner when we use the library.
Here's the Library I wrote - I'm more of a programmer in-training so my OOP knowledge is limited.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
include('../vendor/autoload.php');
use GuzzleHttp\Client;
class Slack {
protected $ci;
private $channel;
private $endpoint;
private $icon;
private $username;
public function __construct()
{
$this->ci =& get_instance();
$this->ci->config->load('slack');
$this->baseUri = $this->ci->config->item('base_uri');
$this->channel = $this->ci->config->item('channel');
$this->endpoint = $this->ci->config->item('endpoint');
$this->icon = $this->ci->config->item('icon');
$this->username = $this->ci->config->item('username');
$this->client = new Client([
'base_uri' => $this->baseUri
]);
}
public function getChannel()
{
return $this->channel;
}
public function setChannel($channel)
{
$this->channel = $channel;
return $this;
}
public function getEndpoint()
{
return $this->endpoint;
}
public function setEndpoint($endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
public function getIcon()
{
return $this->icon;
}
public function setIcon($icon)
{
(mb_substr($icon, 0, 1) == ':')
? $this->iconType = 'icon_emoji'
: $this->iconType = 'icon_url';
$this->icon = $icon;
return $this;
}
public function getIconType()
{
return ($this->iconType) ? $this->iconType : 'icon_emoji';
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function to($channel)
{
$this->setChannel($channel);
return $channel;
}
public function from($username)
{
$this->setUsername($username);
return $username;
}
public function icon($icon)
{
$this->setIcon($icon);
return $icon;
}
public function payload($text)
{
$payload = [
'channel' => $this->getChannel(),
$this->getIconType() => $this->getIcon(),
'link_names' => 1,
'text' => $text,
'username' => $this->getUsername(),
];
return $payload;
}
public function send($text)
{
$payload = json_encode($this->payload($text));
$this->client->post($this->getEndpoint(), [
'body' => $payload
]);
return $this;
}
}
Now I'm using this in our API, which is coded in a Controller, and this is how I am calling the methods:
<?php
// ...
$this->load->library('slack');
$this->slack->icon(':hotdog:');
$this->slack->send('Hello...');
As I said, this works fine...
I wanted though, to be able to do method chaining, like so:
<?php
// ...
$this->slack->icon(':hotdog:')->send('Hello...');
Can you tell me if this is possible and how to achieve it?
Thank you.
As i can see to archive what you want you just need to change that
public function icon($icon)
{
$this->setIcon($icon);
return $icon;
}
to that
public function icon($icon)
{
$this->setIcon($icon);
return $this;
}
and then you will be able to do what you want
$this->slack->icon(':hotdog:')->send('Hello...');
Anyway your icon method no need to return $icon you already have getIcon method
also your send method calling payload method before make request so that should work

Google Maps Engine API Hello World Example in PHP causing MapItem not found

I am trying to work through getting the PHP client for Google Map to work correctly.
I've downloaded a local copy of the GoogleAPI PHP Client from GitHub:https://github.com/google/google-api-php-client.
I am running PHP v5.4 on IIS8. The GoogleAPI was installed in the PHP Include folder, under GoogleAPI.
PHP works correctly with all my other scripts.
I am trying get the example to work from Maps-Engine Documentation.
<?php
ini_set('display_errors','on');
require('GoogleAPI/autoload.php');
//require_once 'GoogleAPI/src/Google/Client.php';
//require_once 'Google/Service/MapsEngine.php';
$apiKey = "API Key";
$client = new Google_Client();
$client->setApplicationName("Google-PhpMapsEngineSample/1.0");
$client->setDeveloperKey($apiKey);
$service = new Google_Service_MapsEngine($client);
$optParams = array('maxResults' => 500, 'version' => 'published');
$results = $service->tables_features->listTablesFeatures("12421761926155747447-06672618218968397709", $optParams);
print_r($results);
?>
The only changes to the code example were the API Key, load the Google Autoloader and comment out the require_once directives.
The output I receive is:
Fatal error: Class 'Google_Service_MapsEngine_MapItem' not found in C:\Program Files (x86)\PHP\v5.4\includes\GoogleAPI\src\Google\Service\MapsEngine.php on line 4702
MapsEngine:4702 extends the Google_Service_MapsEngine_MapItem class. The Google_Service_MapsEngine_MapItem class extends the Google_Model class defined in Model.php file.
Hi I had the same problem.
There is a bug in the google-api-php-client/src/Google/Service/MapsEngine.php file. The class Google_Service_MapsEngine_MapFolder which exends the Google_Service_MapsEngine_MapItem is declared before the class Google_Service_MapsEngine_MapItem is declared.
I switch the order of the 2 classes in the MapsEngine.php file and that fixed the problem. This shows the correct order for the classes.
class Google_Service_MapsEngine_MapItem extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $type;
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_MapsEngine_MapFolder extends Google_Service_MapsEngine_MapItem
{
protected $collection_key = 'defaultViewport';
protected $internal_gapi_mappings = array(
);
protected $contentsType = 'Google_Service_MapsEngine_MapItem';
protected $contentsDataType = 'array';
public $defaultViewport;
public $expandable;
public $key;
public $name;
public $visibility;
protected function gapiInit()
{
$this->type = 'folder';
}
public function setContents($contents)
{
$this->contents = $contents;
}
public function getContents()
{
return $this->contents;
}
public function setDefaultViewport($defaultViewport)
{
$this->defaultViewport = $defaultViewport;
}
public function getDefaultViewport()
{
return $this->defaultViewport;
}
public function setExpandable($expandable)
{
$this->expandable = $expandable;
}
public function getExpandable()
{
return $this->expandable;
}
public function setKey($key)
{
$this->key = $key;
}
public function getKey()
{
return $this->key;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setVisibility($visibility)
{
$this->visibility = $visibility;
}
public function getVisibility()
{
return $this->visibility;
}
}

PHP simple chain class methods without create object

in this below class i want to use class like with static methods and for use class methods without create new object from parent.
for example:
<?php
class Permission
{
protected $permission = false;
protected $id = 0;
public static function __construct()
{
return new static;
}
public function user( $id )
{
$this->id = $id;
}
public function check()
{
$this->permission = true;
}
public function item( $item )
{
return $item;
}
}
$bar = Permission::user(100)->item("HELLO");
print_r($bar);
this code not working and have problem. how to resolve this class problem?
That will not work because user method is not static, try changing this two methods, and this is good way of generating objects
public function __construct($id)
{
$this->id = $id;
}
public static function user( $id )
{
return new static($id);
}
I'd suggest you a singleton pattern, like this
class Permission
{
static protected $permission = false;
static protected $id = 0;
private static $_instance = null;
private function __construct () { }
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function user( $userId )
{
self::$id = $userId;
return self::$_instance;
}
public static function check()
{
self::$permission = true;
return self::$_instance;
}
public static function item( $item )
{
return $item;
}
}
$bar = Permission::getInstance()->user(100)->item("HELLO");
print_r($bar);
You can chain methods in 'dynamic' classes by returning $this at the end of method (remember, you have a static).
class A {
public function someMethod()
{
// some code
return $this
}
public function otherMethod()
{
// some code
return $this
}
$a = new A();
$a->someMethod()->otherMethod();
}

Categories