How do I implement a construct function on public function? - php

Hi I have a problem where I just can't figure out how to implement a construct function on this php that I have here:
class zendesk{
private $client;
function __construct() {
public function sync_organisations() {
$loader = require LIBPATH . 'vendor/autoload.php';
$loader->setPsr4("GuzzleHttp\\", APPPATH . '../vendor/guzzlehttp/guzzle/src/');
$subdomain = "Name";
$username = "name#name.name"; // replace this with your registered email
$token = "token"; // replace this with your token
$client = new ZendeskAPI($subdomain);
$client->setAuth('basic', ['username' => $username, 'token' => $token]);}
Could somebody show me how to implement a public function __construct() {?
Thanks in advance for the help!

PHP Constructors and Destructors
To create a Constructor in PHP use:
public function __construct() {
//Code
}
So for example if you want to call your function sync_organisations() in the constructor, you could do following:
class zendesk{
private $client;
public function __construct() {
$this->sync_organisations();
}
public function sync_organisations() {
$loader = require LIBPATH . 'vendor/autoload.php';
...
}
}

Related

How to pass parameters to a constructor through an interface in PHP

Im using an interface to interact with a class and its methods. How can I pass parameters (user credentials) to the constructor in this class? Ive only managed to make it work by hard coding some parameters in the "Wrapper". Then calling the methods works as it should.
namespace App\Http;
interface WrapperInterface
{
public function __construct(string $id, $secret);
}
class Wrapper implements WrapperInterface
{
public function __construct($id = '', $secret = '')
{
$this->id = $id;
$this->secret = $secret;
$this->curlInit();
}
public function SomeFunction()
{
// some functionality
return $this->SomePrivateFunction();
}
private function SomePrivateFunction()
{
// some functionality
}
}
use App\Http\WrapperInterface;
class SomeCommand
{
private $client
public function __construct(WrapperInterface $client)
{
$this->client = $client;
parent::__construct();
}
public function handle()
{
$this->client->someFunction();
}
}
All of your code is syntactically incorrect.
Classes don't extend interfaces, they implement them.
Classes must implement interface method prototypes exactly.
Class SomeCommand has no parent, so you can't call parent::anything unless you truly want the generic Object class's blank methods/properties.
I've never seen a constructor defined in an interface and it's probably not a good idea, but it doesn't seem to be forbidden, so... fill your boots.
It looks like you want to do composition, which would look like:
interface WrapperInterface {
public function __construct(string $id, $secret);
}
class Wrapper implements WrapperInterface {
protected $id, $secret;
public function __construct(string $id, $secret) {
$this->id = $id;
$this->secret = $secret;
}
public function debug() {
return [ $this->id, $this->secret ];
}
}
class SomeCommand {
private $client;
public function __construct(WrapperInterface $client) {
$this->client = $client;
}
public function debug() {
return $this->client->debug();
}
}
$i = new Wrapper('someid', 'somesecret');
$c = new SomeCommand($i);
var_dump( $c->debug() );
and is actual, runnable code: https://3v4l.org/9L2Uo

Access $app object from controller

How to get access to $app inside a controller as the Slim 3.3 injects only the ContainerInterface?
Code to illustrate the question:
$app = new \Slim\App;
$app->get('/home', 'HomeController:get');
$app->run();
class HomeController {
private $ci;
public function _construct($ci) {
$this->ci = $ci;
}
public function get($request, $response) {
$this->ci->get(...);
// How to access $app and dependencies like $app->jwt?
}
}
This was a tough one.
Slim 3 heavily uses dependency injection, so you might want to use it too.
First inside your dependencies.php you need to grab the $app and throw it in a container to inject it to the Controller later.
$container['slim'] = function ($c) {
global $app;
return $app;
};
Then you got to inject it:
// Generic Controller
$container['App\Controllers\_Controller'] = function ($c) {
return new _Controller($c->get('slim'));
};
Now on your controller.php:
private $slim;
/**
* #param \Psr\Log\LoggerInterface $logger
* #param \App\DataAccess $dataaccess
* #param \App\$app $slim
*/
public function __construct(LoggerInterface $logger, _DataAccess $dataaccess, $slim)
{
$this->logger = $logger;
$this->dataaccess = $dataaccess;
$this->slim = $slim;
}
Now you just got call it like this:
$this->slim->doSomething();
You can make your own 'singleton' to mimic Slim::getInstance(); ;)
class Anorexic extends \Slim\App {
private static $_instance;
public static function getInstance(){
if(empty(self::$_instance){
self::$_instance = new self();
}
return self::$_instance;
}
}
Then change your initialization like this:
// $app = new \Slim\App;
$app = Anorexic::getInstance();
Now you can get your \Slim\App instance anywhere in your code by calling Anorexic::getInstance(); Ofcourse you should never try this at home :P

Accessing PHP variable from static function

I am getting error in below code, cause am not able to access $log in static function Log which gets initialized in _construct.
class Logger extends Singleton{
protected function __construct() {
if(!class_exists("Log")) {
include '/usr/php/Log.php';
}
$MONITORING_LOGFILE = "/var/log/Monitoring.log";
ini_set('error_log', 'syslog');
openlog($MONITORING_LOGFILE, LOG_NDELAY, LOG_LOCAL0);
$log = Log::singleton('syslog', LOG_LOCAL0, $MONITORING_LOGFILE, array('lineFormat' => ' %{message}'), PEAR_LOG_DEBUG);
}
public static function Log($message){
$log->err($message);
}
}
Ok, I modified the above code
class Logger extends Singleton{
private $log;
protected function __construct() {
if(!class_exists("Log")) {
include '/usr/php/Log.php';
}
$MONITORING_LOGFILE = "/var/log/Monitoring.log";
ini_set('error_log', 'syslog');
openlog($MONITORING_LOGFILE, LOG_NDELAY, LOG_LOCAL0);
$this->log = Log::singleton('syslog', LOG_LOCAL0, $MONITORING_LOGFILE, array('lineFormat' => ' %{message}'), PEAR_LOG_DEBUG);
}
public function Log($message){
$this->log->err($message);
}
}
and now its working fine .... just want to confirm if initializng like this is ok in Singleton pattern?
To be able to access the $log variable trough a static function you need to have a reference of it:
class Logger extends Singleton{
private static $log; //static instance of Log::singleton
protected function __construct() {
if(!class_exists("Log")) {
include '/usr/php/Log.php';
}
$MONITORING_LOGFILE = "/var/log/Monitoring.log";
ini_set('error_log', 'syslog');
openlog($MONITORING_LOGFILE, LOG_NDELAY, LOG_LOCAL0);
self::$log = Log::singleton('syslog', LOG_LOCAL0, $MONITORING_LOGFILE, array('lineFormat' => ' %{message}'), PEAR_LOG_DEBUG);
}
//static method
public static function Log($message){
self::$log->err($message);
}
}
To create your instance of the class Logger and access the static Log function you can do the following:
$mylog = new Logger();
$mylog::Log("Your text here");

CodeIgniter use a global session variable from contructor

I need to use a session information in various functions of my controller, but I can't initialize it in the constructor, because I get an error. Message: Undefined property: Soporte::$session
class Soporte extends MY_Controller {
function __construct(){
parent::__construct( $module, $functionality );
}
public function actualizarSolicitud( $id_solicitud ){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
...
}
public function adminHistorico(){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
$config = array();
...
}
...
}
There's a way to initialize a global variable $user?
Try like below, model is quite complicated so I'm not providing it's code, but you should get the point. Any questions let me know.
/**
* This class is used for performing all read/write session operations
* Native php session is utilized (MY_Session library)
*/
class SessionManager extends BaseLibrary {
private $oUser;
public function __construct() {
parent::__construct();
$this->CI->load->model('User');
}
public function setUser(User $oUser) {
$this->CI->session->set_userdata('userId', $oUser->getId());
}
public function getUser() {
if ($this->oUser === null) {
$this->oUser = new User();
if ($this->CI->session->userdata('userId')) {
$this->oUser->setId($this->CI->session->userdata('userId'));
}
}
return $this->oUser;
}
public function logout() {
$this->CI->session->set_userdata('userId', NULL);
}
}

Include Doctrine2 in PHP class

I started with Doctrine2 usage in my projects. Howevery, I don't understand something. Normally, I am working with PHP classes and my problem is:
require_once 'bootstrap.php';
class test {
public function addEmployee($name, $lastname) {
$emp = new Employee();
$emp->name = $name;
... other code
$entityManager->persist($emp);
$entityManager->flush();
}
}
Gives error that entuty manager is noc declared as variable. But, when I include bootstrap.php in function, it works. Like this:
class test {
public function addEmployee($name, $lastname) {
require_once 'bootstrap.php';
$emp = new Employee();
$emp->name = $name;
... other code
$entityManager->persist($emp);
$entityManager->flush();
}
}
I think it will be really slow if I include that in each function, so my question is: Is there any other way to include 'bootstrap.php' for all functions in class?
Use dependency injection. For example
class Test {
/**
* #var \Doctrine\ORM\EntityManager
*/
private $em;
public function __construct(\Doctrine\ORM\EntityManager $entityManager) {
$this->em = $entityManager;
}
public function addEmployee($name, $lastname) {
// snip
$this->em->persist($emp);
$this->em->flush();
}
}
require_once 'bootstrap.php';
$test = new Test($entityManager);

Categories