Laravel php - Do something at the beginning and end of function - php

I'm trying to do something at the beginning and end of each function.
instead of doing so
public function beforeEveryFunctionCore()
{
//something
}
public function afterEveryFunctionCore()
{
//something
}
public function newFunction1(Request $request)
{
$this->beforeEveryFunctionCore();
//function core
$this->afterEveryFunctionCore();
return $something;
}
public function newFunction2(Request $request)
{
$this->beforeEveryFunctionCore();
//function core
$this->afterEveryFunctionCore();
return $something;
}
and so on repeated..(boring)
I would like something like this.
public function beforeEveryFunctionCore()
{
//it does something that is called automatically
}
public function afterEveryFunctionCore()
{
//it does something that is called automatically
}
public function newFunction1(Request $request)
{
//function core
return $something;
}
public function newFunction2(Request $request)
{
//function core
return $something;
}
I know I can do something before every API call with middleware and with construct.
But in this case I talk about any function even those in traits.
How do you think it can be done?

Related

Laravel call service with repository pattern from other service

I'm using repository pattern in my Laravel project.
what is the good pattern to call service from other service?
For example service will looks like this:
class GetAllUsersService
{
private $userRepository;
public function __construct(UserRepository $repository)
{
$this->userRepository = $repository;
}
public function execute()
{
return $this->userRepository->getAll();
}
}
Now if I want to execute this service from other part of the application I will do something like this:
class AnyClass
{
public function executeUserService()
{
$repository = new UserEloquentRepository();
$service = new GetAllUsersService($repository);
return $service->execute();
}
}
Is it correct way to do it? Is there other ways? Maybe some UI layer should be in between?
I think you have three ways to do it:
1) use method __construct();
class AnyClass
{
private $get_all_users_service;
public function __construct(GetAllUsersService $get_all_users_service)
{
$this->get_all_users_service = $get_all_users_service;
}
public function index()
{
$fetchAllUsers = $this->get_all_users_service->fetchAll();
}
}
2) use the specified services like a parameter of each function needs to use them:
class AnyClass
{
public function index(GetAllUsersService $get_all_users_service)
{
$fetchAllUsers = $get_all_users_service->fetchAll();
}
}
3) use method app() of Laravel helper like this:
class AnyClass
{
public function index()
{
$get_all_users_service = app(GetAllUsersService::class);
$fetchAllUsers = $get_all_users_service->fetchAll();
}
}

How to access data of one function to another in laravel

Okay the issue is something like this
I have a function in AController
public function index()
{
$store = Store::(query)(to)(rows)->first();
return view('store.index', compact('store'));
}
Now in the same controller I have another function
public function abc()
{
return view('store.abc');
}
Now to this function I also want to send the compact('store') to the view abc I can just add the query again in the abc() function but that would be lazy and make performance issues. Is there a way that I can access $store object in other functions too?
If I understand you correctly you want to access the same query from two places. So extract getting stores to another method like
private function store()
{
$minutes = 10; // set here
return Cache::remember('users', $minutes, function () {
return Store::(query)(to)(rows)->first();
});
}
Additionally I have cached the query. So it get executed once at a defiened time.
Then access it from other two methods like,
public function index()
{
$store = $this->store();
return view('store.index', compact('store'));
}
public function abc()
{
$store = $this->store();
return view('store.abc', compact('store'));
}
class StoreController extends Controller
{
public function index()
{
return view('admin.store',['data' => $this->getSetting()]);
}
public function getStoreData()
{
//get your data here, for example
$data = Store::where('status',1)->first();
//get all data
//$data = Store::all();
return ($data);
}
}
Try the following. Not testing but it should work for you.
class AController
{
public function getStore()
{
$store = Store::(query)(to)(rows)->first();
return compact('store');
}
public function index()
{
return view('store.index', $this->getStore());
}
public function abc()
{
return view('store.abc', $this->getStore());
}
}

Php remove () in a function to make it easier to use

I am creating a little system which will allow users to extend the system with their own classes.
Class Core {
static $confArray;
static $extendArray;
protected static $instance;
public function read($name)
{
return self::$confArray[$name];
}
public function put($name, $value)
{
self::$confArray[$name] = $value;
}
public function extend($function, $handler, $args=null){
self::$extendArray[$function] = new $handler($args);
}
public function __call($method, $args){
return self::$extendArray[$method];
}
public static function getInstance()
{
if (!isset(self::$instance))
{
$object =__CLASS__;
self::$instance= new $object;
}
return self::$instance;
}
}
With That, now a user can come and register a simple extension from such a class:
class WorkersTest{
function isWorking($who){
echo "$who is working";
}
function isNotWorking($who){
echo "$who is not working";
}
}
To call the function (isworking/ isNotWorking), a the programmer needs to register the test class through:
Core::getInstance->extend("worker","WorkersTest");
Then it can now be called through:
Core::getInstance->worker()->isWorking("George");
This is working perfectly. My question is how i can remove the () in the call (dont worry why) and have:
Core::getInstance->worker->isWorking("George");
Is it possible?
You can use the magic __get() method, just like __call():
public function __get($name)
{
return $this->$name();
}
Try overriding the magic __get() method to return what you need:
Class Core {
// (...)
public function __get($name) {
if (isset( self::$extendArray[$function] )) {
return $this->$name();
}
//if there is no function registered under named "$name"
//throwing Exception is by design better, as #scragar suggested
throw new Exception("No function registered under named {$name}");
//return NULL;
}
}

use muliple method in one object in php [duplicate]

This question already has answers here:
PHP method chaining or fluent interface?
(10 answers)
Closed 9 years ago.
I am new to php and crating classes for my project . I have reached this far ..
$db->select('id');
$db->from('name');
$db->where("idnum<:num");
$db->bindparamers(':num',100);
$rows=$db->executeQuery();
I wana know to create methods such that i can use all thing at once like below
$db->select('id')->from('name')->where('idnum>100')->executeQuery();
I have tried searching but not getting what exactly i should search for
here is my class structure
class Dbconnections
{
//For Complex Queries
public function select($items)
{
}
public function from($tablenames)
{
}
public function where($arr)
{
}
public function orderby($order)
{
}
public function bindparamers($parameter,$value)
{
}
public function executeQuery()
{}
}
What changes i need to make to use it as :
$db->select('id')->from('name')->where('idnum>100')->executeQuery();
It's called method chaining and in your case can be achieved by returning $this from each method.
class Dbconnections
{
public function select($items)
{
// ...
return $this;
}
public function from($tablenames)
{
// ...
return $this;
}
public function where($arr)
{
// ...
return $this;
}
public function orderby($order)
{
// ...
return $this;
}
public function bindparamers($parameter,$value)
{
// ...
return $this;
}
public function executeQuery()
{
// ...
return $this;
}
}

Union results of two functions in php class

I have php class(simple example):
<?php class test{
public function __construct() {
//some code
}
public function __destruct() {
//some code
}
public function echo1 {
//some code
return 1;
}
public function echo2 {
//some code
return 2;
}
}
How could I return results of this two functions echo1 and echo2 in class in one row don't creating two new objects for each function?
$obj= new Test;
echo $obj->echo1().$obj->echo2();
Also, capitalize class names, and you'll need parentheses on those functions:
class Test{
public function __construct() {
//some code
}
public function __destruct() {
//some code
}
public function echo1() {
//some code
return "Hello";
}
public function echo2() {
//some code
return "World";
}
}
$obj= new Test;
echo $obj->echo1()." ".$obj->echo2();
You may have to change your functions a little bit.
...
public function echo1() {
//some code
echo 1;
return $this;
}
public function echo2() {
//some code
echo 2;
return $this;
}
...
Then call it like this.
(new test())->echo1()->echo2();

Categories