Cakephp overide Controller constructer - oop

I would to override constroller constrcuter's like this :
class XControler extends AppController {
public $attr = null;
public __construct(){
$this->attr = new YController();
}
}
But when I do that I take error ! can you explain me why and how I do that with out using requestAction just OOP !
thanks

Controllers are responsible for dealing with end user requests. Each controller action should have a view, and normally you would not want to access the methods from YController inside XController.
What you want to achieve can be done this way:
XController.php
App::uses('YController', 'Controller');
class XController extends AppController {
public $attr;
public $uses = array('Person');
public function __construct($request = null, $response = null) {
$this->attr = new YController();
parent::__construct($request, $response);
}
public function method1() {
// you can now call methods from YController:
$this->attr->Ymethod1();
}
}
YController.php
class YController extends AppController {
public function Ymethod1() {
// ....
}
}
However, the business logic should be inside Models or Components. This is the proper way to share methods between more controllers.
So your XController should look like:
class XController extends AppController {
public $uses = array('Model1');
public function action1() {
$this->Model1->method1();
// ....
}
}

Related

Set & Get session variable value

I am setting session variable in function of a controller like below.
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session(['user_name' => $user_name]);
}
}
I am trying to access that session variable in another function of another controller.
use Illuminate\Support\Facades\Session;
class DashboardController extends Controller
{
public function __construct()
{
dd(session('user_name')); // I am not getting value here
}
}
I am not getting value from Session Variable.
You can do it like this
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session()->put('user_name', $user_name);
}
}
And you can get it another controller or anywhere like this
session()->get('user_name');
Hope this will help you, thanks..

common code for all methods in a controller class

I have 10 controllers that use the same block of code but I can't figure out how to write the code once and use it everywhere.
I have to define an object called:
requiredStructuralSupportParameters
, then set 3 fields in the object.
This is one of the controller methods that uses it:
public class StructureController : Controller
{
public IActionResult Index()
{
var requiredStructuralSupportParameters = new Structure.RequiredInfo()
{
Steel = "1500y",
Concrete = "5500l",
Rebar = "95000y"
};
var response = callToAPI(requiredStructuralSupportParameters);
return response.Results;
}
}
I have tried taking that code out and putting it at the top of the controller class and making it public, but then my controllers can't see it and I get nullreferenceexception errors.
So it only works when I put it directly in the controller methods.
Is there a way to make this so that all controllers can re-use the same block of code?
public class StructureController : Controller
{
protected YourType _requiredStructuralSupportParameters;
public StructureController()
{
this._requiredStructuralSupportParameters = new Structure.RequiredInfo()
{
Steel = "1500y",
Concrete = "5500l",
Rebar = "95000y"
};
}
}
then have your other controllers inherit your StructureController:
public SomeController : StructureController{
public IActionResult Index() {
var response = callToAPI(this._requiredStructuralSupportParameters);
return response.Results;
}
}
haven't tested it but i hope you get an idea

OOP - Override init method called in constructor

I have a simple class hierarchy of two classes. Both classes call an init-method specific to that class. Therefor the init-method is overriden in the subclass:
class A
{
public A() { this->InitHandlers(); }
public virtual void InitHandlers() { // load some event handlers here }
}
class B: public A
{
public B() { this->InitHandlers(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
I know this is evil design:
The call of an overriden method from constructor is error-prone.
B::InitHandlers() would be called twice with this setup.
But semantically it makes sense to me: I want to extend the behaviour of class A in class B by loading more handlers but still keeping the handlers loaded by class A. Further this is a task that has to be done in construction. So how can this be solved with a more robust design?
You can do something like this:
class A
{
protected boolean init = false;
public A() { this->Init(); }
public virtual void Init() {
if (!this->init) {
this->init = true;
this->InitHandlers();
}
}
public virtual void InitHandlers() {
// load some event handlers here
}
}
class B: public A
{
public B() { this->Init(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
You can see it as a design pattern template method.

Laravel Mashape/Unirest API package and Interface

How do you implement interface for external package in Laravel? Say, I want to use Mashape/Unirest API to get analyse of text, but in future I would like to switch to other API provider and do not change to much in code.
interface AnalyzerInterface {
public function analyze(); //or send()?
}
class UnirestAnalyzer implements AnalyzerInterface {
function __constructor(Unirest unirest){
//this->...
}
function analyze($text, $lang) {
Unirest::post(.. getConfig() )
}
//some private methods to process data
}
And where to put that files interfece and UnirestAnalyzer? Make special folder for them, add to composer? Add namespace?
This is how I would go to Interface and Implement something like this:
interface AnalyzerInterface {
public function analyze();
public function setConfig($name, $value);
}
class UnirestAnalyzer implements AnalyzerInterface {
private $unirest;
private $config = [];
public function __construct(Unirest unirest)
{
$this->unirest = $unirest;
}
public function analyze($text, $lang)
{
$this->unirest->post($this->config['var']);
}
public function setConfig($name, $value)
{
$this->config[$name] = $value;
}
//some private methods to process data
}
class Analyser {
private $analizer;
public function __construct(AnalyzerInterface analyzer)
{
$this->analyzer = $analyzer;
$this->analyzer->setConfig('var', Config::get('var'));
}
public function analyze()
{
return $this->analyzer->analyze();
}
}
And you must bind it on Laravel:
App::bind('AnalyzerInterface', 'UnirestAnalyzer');

Autofac: how do I pass a reference to the component being resolved to one of its dependents?

With the following:
public class AClass
{
public ADependent Dependent { get; set; }
}
public class ADependent
{
public ADependent(AClass ownerValue) {}
}
with the following registrations...
builder.RegisterType<AClass>().PropertiesAutowired().InstancePerDependency();
builder.RegisterType<ADependent>().PropertiesAutowired().InstancePerDependency();
When I resolve an AClass, how do I make sure that 'ownerValue' is the instance of AClass being resolved, and not another instance? Thx
FOLLOW ON
The example above doesn't really catch the problem properly, which is how to wire up ADependent when registering when scanning... for example
public class AClass : IAClass
{
public IADependent Dependent { get; set; }
}
public class ADependent : IADependent
{
public ADependent(IAClass ownerValue) {}
}
// registrations...
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IAClass>()
.As<IAClass>()
.InstancePerDependency()
.PropertiesAutowired();
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IADependent>()
.As<IADependent>()
.InstancePerDependency()
.PropertiesAutowired();
The function I am looking for really is another relationship type like
public class ADependent : IADependent
{
public ADependent(OwnedBy<IAClass> ownerValue) {}
}
The OwnedBy indicates that ownerValue is the instance that caused ADependent to created. Does something like this make sense? It would certainly make wiring up UI components a breeze.
To extend Steven's approach, you can even Resolve() the second class, passing the first instance as a parameter:
builder.RegisterType<ADependent>();
builder.Register<AClass>(c =>
{
var a = new AClass();
a.Dependent = c.Resolve<ADependent>(TypedParameter.From(a));
return a;
});
You can register a lambda to do the trick:
builder.Register<AClass>(_ =>
{
var a = new AClass();
a.Dependent = new ADependent(a);
return a;
});