How to create system like System()->parameter()->parmKey or like
it's return value 123
parmKey not fixed it's a change or dynamically
I am not sure, how can implement this system in laravel
this is feature in php oop named Chaining methods
example :
<?php
class Message
{
public $message;
function __construct()
{
$this->message = "";
}
public function newLine($line)
{
$this->message .= $line;
return $this;
}
public function getMessage()
{
return $this->message;
}
}
$message = new Message();
echo $message->newLine('Hello')->newLine('My name is yazan')->getMessage();
Related
I'm trying to write my custom laravel channel notifications, like this: https://laravel.com/docs/5.7/notifications#custom-channels.
I wrote this code:
AimonChannel.php
class AimonChannel{
public function send($notifiable, Notification $notification)
{
$message = $notification->toAimon($notifiable);
if (is_string($message)) {
$message = new AimonMessage($message);
}
//some code to send sms with curl
}
AimonMessage.php
class AimonMessage
{
public $messaggio = "";
public function messaggio($messaggio){
$this->messaggio = $messaggio;
}
}
SendAimonMessage.php
class SendAimonMessage extends Notification
{
use Queueable;
protected $messaggio;
public function __construct($messaggio)
{
$this->messaggio = $messaggio;
}
public function via($notifiable)
{
return [AimonChannel::class];
}
public function toAimon($notifiable)
{
return (new AimonMessage())
->messaggio($this->messaggio);
}
}
So, the code:
$user->notify(new SendAimonMessage('my custom message'));
is sent, but without the text.
The problem is in the send() function of AimonChannel; the $message variable is always null.
Where is my code mistake?
Thanks!
add return statement in the messaggio function like this:
class AimonMessage {
public $messaggio = "";
public function messaggio($messaggio){
$this->messaggio = $messagio;
return $this;
}
}
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.
I want to modify this code:
function send($message, $mode, $param1, $param2)
{
$msg = ">> " . $message;
if ($mode == "client") {
$client = $param1; // $param1 is a websocket source variable
// code
}
elseif ($mode == "clients") {
$clients = $param1; // now $param1 is an array of websocket sources
// code
}
elseif ($mode == "all") {
// code
}
}
send("Hello World!", "all", $whatever1, $whatever2);
(this function actually reads $mode to understand what it is going to do)
to the code below.
This code WILL NOT work. I would you like to tell me what changes i have to do for it to work
class send($message)
{
$msg = ">> " . $message;
public function client($client, $param2) { // $client is $param1 of previous code
// code using $msg
}
public function clients($clients, $param2) { // $clients is an array and the $param1 of previous code
// code using $msg
}
public function all($param2) {
// code using $msg
}
}
send("Hello World!")::all($whatever2);
I know the second code is very messed up. It doesn't work, but I want to do something like this. To categorize functions and parameters. I hope you got the idea. Maybe there is no such way and I have to use the $mode method in the first code?
You are trying to decompose the function and create a class from the parts.
There are some syntax errors in your code.
You are mixing up a lot of concepts here: functions, classes, static and dynamic calls. Please read the basic chapters in the PHP manual about OOP: http://php.net/manual/en/language.oop5.php
This part is wrong.
class send($message)
{
A class definition begins with the keyword class, followed by a class name:
class Send {
}
You can not use this directly inside a class, you could wrap it in the constructor or in a function.
$msg = ">> " . $message;
You can declare a constructor which accepts a parameter:
public function __construct($message) {
$this->message = $message;
}
class Send
{
private $message = '';
public function __construct($message) {
$this->message = $message;
}
public function toClient($client, $param) {
var_dump($this->message, $client, $param);
}
public function toClients($clients, $param) {
var_dump($this->message, $clients, $param);
}
public function toAll($param) {
var_dump($this->message, $param);
}
}
This class accept the message in the constructor and sets it as a property.
You might then reuse it across the functions ($this->message).
// Usage
$message = 'Hello World';
// instantiate the class
// and pass the message you want to send as param
// execute a specific class method
$send = new Send($message);
$send->toClient('john', 'more');
// with PHP 5.4 it's a one-liner
(new Send($message))->toClient('john', 'more');
I figured it out, many many thanks to Jens A. Koch
For all of you out there:
Prior to PHP 5.4:
class send {
public function __construct($msg) {
$this -> message = $msg;
}
public function clients(/* many params */) {
echo "some clients say: ".$this->message;
}
public function client(/* many params */) {
echo "one client says: ".$this->message;
}
public function all(/* many params */) {
echo "all clients say: ".$this->message;
}
// function b (build) returns the class
public function b($msg) {return new self($msg);}
}
// CALLING IT
send::b("test")->clients(); // >> some clients say: test
PHP 5.4+ (unfortunately I have 5.3 but it should work)
"public function b" is not needed:
class send {
public function __construct($msg) {
$this -> message = $msg;
}
public function clients(/* many params */) {
echo "some clients say: ".$this->message;
}
public function client(/* many params */) {
echo "one client says: ".$this->message;
}
public function all(/* many params */) {
echo "all clients say: ".$this->message;
}
}
// CALLING IT
(new send("test"))->clients();
I need to reconstruct head scripts and links so I would like to create a class that I can use for future references.
I started like :
class HeadClas{
public static $headprint;
function __construct(){
$this->headprint = "";
}
function addLinks(){
$this->headprint .= "addLinks";
return $this;
}
function addMeta(){
$this->headprint .= "addMeta";
return $this;
}
function printHead(){
return $this->headprint;
}
}
In the above case I would need to do
$print = new HeadClas;
$print->addLinks()->addMeta();
and I would like to do
$print = new HeadClas;
$print->printHead();
I did try
function printHead(){
return $this->addMeta()->addLinks();
}
But than I need to do
$print->printHead()->headprint;
What am I missing here?
Any help is appreciated!
Firstly, you should make the $headprint field non static. Making it static makes it the same reference for all future instances which will create undesirable results.
The printHead() should print the contents of that field like the method name suggests.
class HeadClass {
public $headprint;
function __construct() {
$this->headprint = "";
}
function addLinks() {
$this->headprint .= "addLinks";
return $this;
}
function addMeta() {
$this->headprint .= "addMeta";
return $this;
}
function printHead() {
$this->addLinks()->addMeta();
echo $this->headprint;
}
}
$printer = new HeadClass();
$printer->printHead();
So i am new to oo php and i-m building a sample app for learning purpses , one thing i must do is load a language file according to some settings
The code, as you will discover below is divided between two classes , a settings class witch should load the language file and another class in this case "contact" witch should read the array in the language files and display the propper message.
this is the Settings class
the lang variable sets the default language it can take 2 values at the moment : ro- for romanian and en - for english ,
class Settings
{
static public $lang = 'ro';
static public $load;
static public function get_language()
{
if(self::$lang == 'ro')
{
self::$load = require 'ro.php';
}
elseif(self::$lang == 'en')
{
self::$load = require 'en.php';
}
return self::$load;
}
}
The second class :
class Contact extends Settings {
//proprietati
public $nume;
public $subiect;
public $mesaj;
public $dincs;
//comportament - metode
public function __construct()
{
//$this->dincs = 'Din construct';
parent::get_language();
}
public function write_file()
{
if(empty($this->nume))
{
return $mess['name_error'];
}
else
{
$fp = fopen('data.txt', 'w');
fwrite($fp, $this->nume.".".$this->subiect .".". $this->mesaj."|".$this->dincs ."|".parent::$load);
fclose($fp);
return $mess['file_written'];
}
}
}
A sample from the language file:
$mess = array ("name_error" => "You must insert your name",
"file_written" => "the file has been written",
);
I have looked up on google , and tried some other stuff and can't seem to get it to work , and that may be because i am approaching this problem incorectly.
Plese help.
`
class Settings
{
protected $language = 'ro';
protected $load;
public function setLanguage($language = 'ro')
{
$this->language = $language;
// file_get_contents()
$this->load = require($this->language . '.php');
}
public function getLanguage()
{
return $this->language;
}
}
class Contact extends Settings
{
protected $name;
protected $subject;
protected $message;
protected $dincs;
protected $settingsObject;
// set all the properties below...
public function setName($name)
{
$this->name = $name;
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function setMessage($message)
{
$this->message = $message;
}
public function setDincs($dincs)
{
$this->dincs = $dincs;
}
// get all the properties...
public function getName()
{
return $this->name;
}
// This function only accepts an instance of Settings as the parameter
public function setSettingsObject(Settings $settings)
{
$this->settingsObject = $settings;
}
public function writeContentsToFile()
{
// if there is nothing in name, throw a new exception
if (empty($this->name))
{
throw new Exception('name has not been set! Set name before calling '. __METHOD__);
}
else
{
// get the file
$fp = fopen('data.txt', 'w');
// formatted string
$contents = sprintf('%s . %s . %s | %s | %s', $this->name, $this->subject, $this->message, $this->dincs, $this->settingsObject->getLanguage());
// write to the file
fwrite($fp, $contents);
// close the handler
fclose($fp);
return ('File written! Contents written: ' . $contents);
}
}
}
// instantiate settings
$settings = new Settings();
$settings->setLanguage('en');
// instantiate contact and set the settings object
$contact = new Contact();
$contact->setName('Joe Smith'); // if this is not set, ::writeContentsToFile will throw an Exception
$contact->setSettingsObject($settings);
// try and catch the Exception that ::writeContentsToFile may throw
try
{
echo $contact->writeContentsToFile();
}
catch (Exception $exception)
{
var_dump($exception);
}
?>
`
self::$load = require 'en.php';
You assign here a return value from the file inclusion to self::$load; not the variable $mess you defined in your language file.
So, there are two ways now: return the array $mess (return $mess;) from the language file.
Or you can just write:
require 'en.php';
self::$load = $mess;
Little side note: I'd check in your Settings::getLanguage() method if (self::$load) and return then the self::$load variable instead of refetching the language fileā¦)