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);
Related
I have this file root/core/Router.php
<?php
namespace Core;
class Router {
protected $url;
protected $controller;
private function parseURL() {
// threat the $this->url; for example ["r", "product"]
}
private function request() {
$this->controller = Controller::get($this->url[1]);
}
public function __construct() {
$this->parseURL();
$this->request();
}
}
?>
then file root/core/Controller.php
<?php
namespace Core;
class Controller {
public static function model($name, $params = []) {
$model = "\\Model\\$name";
return new $model($params);
}
public static function view($name, $params = []) {
require_once APP_DIR . "view/" . $name . ".php";
}
public static function get($name, $params = []) {
require_once APP_DIR . "controller/" . $name . ".php";
$name = "\\Controller\\$name";
return new $name($params);
}
}
?>
then root/controler/Product.php
<?php
namespace Controller;
use Core\Controller;
use Model\Product;
class Product {
public function get() {
$ret['state'] = 510;
$productModel = new Product;
$products = $productModel->getAll();
if(isset($products)) {
$ret['products'] = $products;
$ret['state'] = 200;
}
return $ret;
}
}
?>
then file root/model/Product.php
<?php
namespace Model;
class Product {
public function add($values) {
return Database::insert("product", $values);
}
}
?>
and root/core/Model.php
<?php
namespace Core;
class Model {
protected $table = null;
public function getAll() {
// some code to collect data
}
}
?>
What i want to achive is that every Controller in root/controller/*.php able to load any Model in root/model/*.php but class inside root/model/*.php must able to access (inheritance/extends) the Model class inside root/core/Model.php i firstly asked on chatGPT for some AI Generated answer, that the reason why i get this far.
Then i get this error, when the AI keep giving the same answer.
Fatal error: Cannot declare class Controller\Product because the name is already in use in C:\xampp\htdocs\app\shop\controller\Product.php on line 6
I actually realize that the simple way probably with naming the class so ther no conflict between it but i became aware how to properly using the namespace if its such features in php. Those files loaded without any autoloader, so i just require_once each file in root/init.php file.
I read few documentations but hard to implement in multiple files and directorys.
I Apreciate any feedback, thanks
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';
...
}
}
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
I try to inherit multiple classes from each other, but something wrong happens somewhere. The classes are the following:
Part of the MobilInterface class:
class MobileInterface
{
private $config;
private $errorData;
private $data;
private $output;
private $job;
public $dbLink;
public function __construct($config) {
$this->config = $config;
}
public function initialize($job) {
$this->dbLink = $this->createDbInstance($this->config);
require_once 'jobs/' . strtolower($this->config->joblist[$job]) .'.php';
$this->job = new $this->config->joblist[$job]($this);
}
public function run($params) {
$job = $this->job;
$this->data = $this->job->run($_GET);
}
}
Mobil Interface is the main interface, which calls the Kupon class based on a string in the $config. My problem is that i want more Kupon like classes and wanted to make a BaseJob class to be able to write each Job class without the constructor.
The problem is that the Kupon class can't see the $dbLink and the $config variables.
The BaseJob class:
<?php
class BaseJob
{
public $interface;
public $dbLink;
public $config;
public function __construct(MobileInterface $interface) {
$this->interface = $interface;
$this->config = $this->interface->get('config');
$this->dbLink = $this->interface->get('dbLink');
}
}
?>
And the Kupon class:
function __construct(){
parent::__construct(MobileInterface $interface);
}
}
?>
I've never worked before with polymorphism. I just heard about it when this question came up.
I have a little backend with 2 permissions. Admin/Normal User. Depending on the permission, i want to display a different navigation, less or more options on the forms etc. But i don't want to create a form for each permission but rather disable the elements i don't need etc.
How would i go with that?
At the moment, i'm using something like that: (Which isn't really polymorphism)
<?php
class My_Resources_ResourceLoader extends Zend_Application_Resource_ResourceAbstract {
public $templateForm = null;
public $customerForm = null;
function init() {
$permission = 'admind';
if($permission == 'admin') {
$this->templateForm = new Application_Form_newTemplate;
} else {
$form = new Application_Form_newTemplate;
$form->removeElement('newTemplate_customer');
$this->templateForm = $form;
}
return $this;
}
}
And in my controller e.g.
<?php
$bootstrap = $this->getInvokeArg('bootstrap');
$xx = $bootstrap->getResource('ResourceLoader');
$this->view->test = $xx->templateForm;
The roles never gonna change. This will probably be okay but isn't the very best solution. What would be a better approach to this?
I've thrown away the approach above and now use real polymorphism like this:
at Application/Model got an interface like:
And 2 Classes like:
<?php
class Application_Model_TemplateUser implements Application_Model_TemplateInterface {
private $table = null;
private $row = null;
private $id = null;
private $formValues = null;
function __construct() {}
public function exist() {}
public function save() {}
public function getCustomerId($name) {}
public function update() {}
public function getForm() {
$form = new Application_Form_newTemplate;
$form->removeElement('newTemplate_customer');
return $form;
}
}
And
<?php
class Application_Model_TemplateAdmin implements Application_Model_TemplateInterface {
private $table = null;
private $row = null;
private $id = null;
private $formValues = null;
function __construct() {}
public function exist() {}
public function save() {}
public function getCustomerId($name) {}
public function update() {}
public function getForm() {
return new Application_Form_NewTemplate();
}
}
In my Controller i do:
<?php
$permission = 'User'; //TODO: Get from Session
$class = 'Application_Model_Template' . $permission;
$xx = new $class;
$form = $xx->getForm();
$this->view->test = $form;
This are just examples. But i think like that I'm really on a better way. Maybe i'm going to use abstract classes since i'm using Zend_Db-Table_Row, which is always the same for updating a row, so it would make more sense using a abstract class instead of an interface.
Nice article about Polymorphism in PHP: http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/