Closed fkwl closed 8 years ago
How do you use your BaseController? If you use static methods (like in the documentation) then you don't instantiate the class / don't call its constructor.
I want a project with MVC, and a route is : Flight::route('/', ['HomeController', 'index']); BaseController is parent C, then __construct didn't work in BaseController, i'm a chinese, English is not good ...
BaseController ` <?php namespace App\Controllers; /**
基类控制器 */ class BaseController { public static $_time; // 当前时间
public function __construct() { echo 123123; self::$_time = time(); }
public static function redirect($url, $code = 200) { \Flight::redirect($url, $code); // Redirects to another URL. } . . . . . . } `
SubscribeController ` <?php namespace App\Controllers\Api; use App\Controllers\BaseController;
/**
class SubscribeController extends BaseController { public function index() { $email = self::request()->query->email; $verify_code = self::request()->query->verify_code; $user = UserModel::where('email', '=', $email) ->where('verify_code', '=', $verify_code) ->where('end_time', '>', self::$_time) ->first(); if(!$user) { self::failure(401); }
$user->verify_time = self::$_time;
$user->status = 1;
}
} `
routes ` Flight::route('/', ['App\Controllers\HomeController', 'index']);
// 订阅 Flight::route('POST /sub', ['App\Controllers\SubscribeController', 'add']); `
self::$_time
no value, means __construct didn't work in BaseController, so why?
` <?php namespace App\Controllers; /**
HomeController */ use App\Librarys\Mail; class HomeController { function __construct() { echo 123; }
function index() { // var_dump(Mail::send_mail_active('shenfakuan@163.com', 'http://www.baidu.com')); self::render('home/index'); } } `
and this __construct didn't work too
Change this:
Flight::route('/', ['App\Controllers\HomeController', 'index']);
Flight::route('POST /sub', ['App\Controllers\SubscribeController', 'add']);
to:
Flight::route('/', [new App\Controllers\HomeController, 'index']);
Flight::route('POST /sub', [new App\Controllers\SubscribeController, 'add']);
and __construct
will work.
@tamtamchik that's bad idea, the __construct will work in each route at the same time, and here , twice
@shenfakuan this is just example how to make flight routes work with objects
@tamtamchik all right, thank you
You can just create a new instance in the callback and call it directly.
Flight::route('/', function() {
$controller = new App\Controllers\HomeController();
$controller->index();
});
@mikecao ok, it's work, thanks man.
I think flightphp should support this approach.
Flight::route('/', ['\\App\\Controllers\\HomeController', 'index']);
This is not difficult to achieve
$a = '\\my\\aaa';
$aa = new $a;
My __construct didn't work in my BaseController, why ?
` class BaseController { public static $_time; // 当前时间
`
there is no echo....