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");
Related
I am trying to display an array of messages at the end of my PHP class. My message handler is working, but only if I "add_message" from within the main parent class and not if I call this function from within a child class. Sorry if this is vague but was not sure how to word the question.
TLDR; How can I add a message from within class Example?
MAIN PARENT CLASS
class Init {
public function __construct() {
$this->load_dependencies();
$this->add_messages();
$this->add_msg_from_instance();
}
private function load_dependencies() {
require_once ROOT . 'classes/class-messages.php';
require_once ROOT . 'classes/class-example.php';
}
public function add_messages() {
$this->messages = new Message_Handler();
$this->messages->add_message( 'hello world' );
}
// I Would like to add a message from within this instance....
public function add_msg_from_instance() {
$example = new Example();
$example->fire_instance();
}
public function run() {
$this->messages->display_messages();
}
}
MESSAGE HANDLER
class Message_Handler {
public function __construct() {
$this->messages = array();
}
public function add_message( $msg ) {
$this->messages = $this->add( $this->messages, $msg );
}
private function add( $messages, $msg ) {
$messages[] = $msg;
return $messages;
}
// Final Function - Should display array of all messages
public function display_messages() {
var_dump( $this->messages );
}
}
EXAMPLE CLASS
class Example {
public function fire_instance() {
$this->messages = new Message_Handler();
$this->messages->add_message( 'Hello Universe!' ); // This message is NOT being displayed...
}
}
Because you want to keep the messages around different object, you should pass the object or use a static variable.
I would use a static variable like so:
class Init {
public function __construct() {
$this->load_dependencies();
$this->add_messages();
$this->add_msg_from_instance();
}
private function load_dependencies() {
require_once ROOT . 'classes/class-messages.php';
require_once ROOT . 'classes/class-example.php';
}
public function add_messages() {
// renamed the message handler variable for clarity
$this->message_handler = new Message_Handler();
$this->message_handler->add_message( 'hello world' );
}
// I Would like to add a message from within this instance....
public function add_msg_from_instance() {
$example = new Example();
$example->fire_instance();
}
public function run() {
$this->message_handler->display_messages();
}
}
class Message_Handler {
// use a static var to remember the messages over all objects
public static $_messages = array();
// add message to static
public function add_message( $msg ) {
self::$_messages[] = $msg;
}
// Final Function - Should display array of all messages
public function display_messages() {
var_dump( self::$_messages );
}
}
class Example {
public function fire_instance() {
// new object, same static array
$message_handler = new Message_Handler();
$message_handler->add_message( 'Hello Universe!' );
}
}
// testing...
new Init();
new Init();
$init = new Init();
$init->add_msg_from_instance();
$init->add_msg_from_instance();
$init->add_msg_from_instance();
$init->run();
Although global variables might not be the best design decision, you have at least two approaches to achieve what you want:
Use singleton.
Nowadays it is considered anti-pattern, but it is the simplest way: make message handler a singleton:
class MessageHandler
{
private static $instance;
private $messages = [];
public static function instance(): self
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
}
public function addMessage($message): self
{
$this->messages[] = $message;
return $this;
}
public function messages(): array
{
return $this->messages;
}
}
Then instead of creating a new instance of MessageHandler access it via the static method MessageHandler::instance(). Here is a demo.
Use DI container to inject the same instance (that is created once and held in the container) into all instances that need to access it. This approach is more preferable, but harder to implement in the project where there is no DI container available in the first place.
Edit: Original example removed as it was complex.
The codes provided below doesn't work. I am trying to access the methods defined in a class which is declared in the parent class.
Here is a sample code. Its not working and I'd like to know why
<?php
function & get_instance()
{
return Main::get_instance();
}
class Db{
function select($var)
{
echo $var;
}
}
class Main
{
public $db ;
public $process ;
private static $instance;
function __construct()
{
self::$instance = &$this;
$this->db = new Db ;
$this->process = Process;
}
public static function & get_instance()
{
return self::$instance;
}
}
class Process{
private $main ;
function __construct()
{
$this->main = get_instance() ;
}
function processPayment()
{
$this->main->db->select("hello");
}
}
$main = new Main ;
$main->process->processPayment();
To access members of a parent class, you will have to declare those members protected or public.
For example:
public var $db;
protected var $orders;
I am trying to initiate a class on demand.
class MyClass{
private $modules = array("mod1" => false);
public function __get($name){
if(array_key_exists($name, $this->modules) && !$this->modules[$name]){
$class = ucfirst($name);
$this->$name = new $class();
$this->modules[$name] = true;
}
}
}
I then have another class, which then extends the above class. If I do the following the class doesn't get initiated, and I get an error Fatal error: Call to a member function get() on a non-object
class Home extends MyClass{
public function main(){
echo $this->mod1->get("cat");
}
}
But if I do this, the class does get initiated.
class Home extends MyClass{
public function main(){
$this->mod1;
echo $this->mod1->get("cat");
}
}
Is there any way for me to initiate the class without having to add that extra line?
Just return it after it's instantiated:
class MyClass{
private $modules = array("mod1" => false);
public function __get($name){
if(array_key_exists($name, $this->modules) && !$this->modules[$name]){
$class = ucfirst($name);
$this->$name = new $class();
$this->modules[$name] = true;
return $this->$name;
}
}
}
Now you can do what you want:
class Home extends MyClass{
public function main(){
echo $this->mod1->get("cat");
}
}
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 have this code and i´m trying to use a object
<?php
class Controller {
public $_view;
public function __construct() {
$this->_view = new View();
return $this->_view;
}
}
class View {
public $_params = array ();
public function set_params($index_name,$valores) {
$this->_params[$index_name] = $valores;
}
public function get_param($index_name){
return $this->_params[$index_name];
}
}
?>
i would like to do this:
class Index extends Controller {
public function index() {
$model = Model::get_estancia();
$usuarios = $model->query("SELECT * FROM usuarios");
$this->_view->set_params(); // cant be used.
$this->load_view("index/index");
}
}
i would like to use the set_parms function.
but i can't see the View Function, then i can not use.
Can someone explain and advise me a good and safe way?
Correction from Phil: If a __construct() method isn't found, PHP will revert to legacy constructor syntax and check for a method with the same name as the object. In your case the method index() is being treated as the constructor, and is preventing the parent's constructor from loading the view object into the $_view property.
You can force a class to inherit a parent's constructor by defining __construct() in the child and calling the parent's constructor:
public function __construct() {
parent::_construct();
}
Here is the fixed code:
<?php
class Controller {
public $_view;
public function __construct() {
$this->_view = new View();
return $this->_view;
}
}
.
class View {
public $_params = array ();
public function set_params($index_name,$valores) {
$this->_params[$index_name] = $valores;
}
public function get_param($index_name){
return $this->_params[$index_name];
}
}
.
class Index extends Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$model = Model::get_estancia();
$usuarios = $model->query("SELECT * FROM usuarios");
$this->_view->set_params(); // cant be used.
$this->load_view("index/index");
}
}