Line in Linus
Line in Linus

Reputation: 420

Default code for almost all controllers

I've got a quite few rows and variables in my __construct() that are to be should initiated and passed thru to the methods within my controllers.

Now I've got them in __construct()

 class myController extends Controller {  

      public function __construct()
      {
            $this->pageTitle= DB::(...)
            $this->user = Auth::(...)
            (+100 rows)
      } 

      public function index()
      {
            echo $this->pageTitle;
      }

 }

Since incluce() doesn't work with classes and __construct(), and the exact rows above are used in 60% of my controllers, how do I do to implement the code more easily from one source?

Edit:
It's a multi-site ini'ed with wildcard-subdomains.

The 100 rows consist of ie:

Thiese are all the same for 60%+ of the pages and controllers (both mysql-fetched-pages and in-site applications)

Upvotes: 0

Views: 56

Answers (2)

Björn
Björn

Reputation: 5876

You could create a BaseController which gets extended by all the controllers that need these shared variables.

BaseController.php

<?php 

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class BaseController extends Controller
{
    public function __construct(){
        $this->foo = 'foo';
        $this->bar = 'bar';
    } 
}

TestController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\BaseController;

class TestController extends BaseController
{
    public function index()
    {
        dump($this->foo);
        dump($this->bar);
    }
}

Routes.php

Route::get('test', 'TestController@index');

Result:

"foo"
"bar"

But still i am curious about the 100+ rows or variables you want to add, it sounds like something that perhaps can be optimised. Could you give more info about this?

Upvotes: 1

thepiyush13
thepiyush13

Reputation: 1331

Does this help you ?

<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// we've called a class ***
$obj = new myClass();
?>

https://www.php.net/manual/en/function.autoload.php

Upvotes: 0

Related Questions