How do I init every parent method before init? - zend-framework

I have a custom bootstrap class and I'm extending it.
class Bootstrap extends MyBootstrap
{
}
MyBootstrap.php class have some _init methods. I need it to load all MyBootstrap methods first. How to?

Try something like this inside the Bootstrap class:
$methods = get_class_methods ('MyBootstrap');
foreach ($methods AS $method) {
if (str_pos ($method, '_init') !== false) {
call_user_func (array ($this, $method));
}
}
get_class_methods - returns the class methods' names. Then look for methods like '_init' and run them.

Related

InversifyJS - Inject middleware into controller

I'm using inversify-express-utils using the shortcut decorators (#GET, #POST...) within a node application.
Is it possible to inject middleware into the controller to use with these decorators?
Example of what I'm trying to achieve (doesn't work):
export class TestController implements Controller {
constructor(#inject(TYPES.SomeMiddleware) private someMiddleware: ISomeMiddleware) {}
#Get('/', this.someMiddleware.someMiddlewhereMethod())
public test() {
...
}
}
Like #OweR ReLoaDeD said, currently you can't do that with middleware injected through the controller constructor, due to the way decorators work in TypeScript.
However, you can achieve the same effect by wrapping the controller definition in a function that accepts a kernel, like so:
controller.ts
export function controllerFactory (kernel: Kernel) {
#injectable()
#Controller('/')
class TestController {
constructor() {}
#Get('/', kernel.get<express.RequestHandler>('Middleware'))
testGet(req: any, res: any) {
res.send('hello');
}
}
return TestController;
}
main.ts
let kernel = new Kernel();
let middleware: express.RequestHandler = function(req: any, res: any, next: any) {
console.log('in middleware');
next();
};
kernel.bind<express.RequestHandler>('Middleware').toConstantValue(middleware);
let controller = controllerFactory(kernel);
kernel.bind<interfaces.Controller>(TYPE.Controller).to(controller).whenTargetNamed('TestController');
let server = new InversifyExpressServer(kernel);
// ...
UPDATE
I added an example to the inversify-express-examples repo that showcases this approach using both custom and third-party middleware.
You should be able to use middleware please refer to the following unit tests as an example.
Update
I don't think that is possible because decorators are executed when the class is declared. The constructor injection takes place when the class instance is created (which is after it has been declared). This means that, when the decorator is executed, this.someMiddleware is null.
I'm afraid you won't be able to inject the middleware into the same class that uses it but you can do the following:
import { someMiddlewareMethod} from "middleware";
class TestController implements Controller {
#Get('/', someMiddlewareMethod())
public test() {
// ...
}
}
This is not a limitation of InversifyJS this is a limitation caused by the way decorators work.

How to integrate non Laravel related classes in framework?

I have a class which I would like to use inside of my Laravel App. Where do I place this and how do I integrate in Laravel workflow
what I tried
creating
/app/libraries
--myClass.php
than in composer
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/services",
"app/facades",
"app/libraries",
"public/site"
]
},
composer dump-autoload
Than I would like to initiate inside of a custom Model How would I do that?
under vendor/composer/autoloaded the class is present
than in my model I init autoloaded
public function MyMethod(){
$instance = new MyClass();
var_dump($instance);
// pulled Error : Class 'App\Models\MyClass' not found
}
The work is almost done, now you have to make sure your class appears in
vendor/composer/autoload_classmap.php
Then you just need to use it anywhere:
class Post extends Eloquent {
public function doThing()
{
$instance = new MyClass;
}
}
If you are somehow using namespaces, you have to use them in the top of your class:
use MyClass;
use App\Classes\MyOtherClass;
class Whatever {
public function MyMethod()
{
$instance = new MyClass();
$other = new MyOtherClass();
var_dump($instance);
}
}

Variables available in all controllers?

Where and how to set variable value that is available in all controllers. I don't wont to use zend registry and don't want to extend Zend_Controller_Action. Is there is another way? I just want for example to set:
$a = "test";
and in Index controller to dump it:
class IndexController extends Zend_Controller_Action {
public function indexAction(){
var_dump($a);
}
}
Global vars ruin the purpose of object oriented programming... use namespace or custom configs.
Solution 1
Use session Zend_Session_Namespace, here is documentation on how to Zend_Session_Namespace.
Set set the value in namespace in bootstrap or something (wherever you see fit)
Retrieve the value from namespace in you controller/model/other
Solution 2
Alternatively, you can create some new class with static properties and use it's setters/getters to set and retrieve values.
E.g.
class SomeClass
{
static $hello = 'world';
}
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
var_dump(SomeClass::$hello);
}
}
You can add variables to the request object:
$this->getRequest()->setParam('a', 'hello');
Then retrieve it using:
$this->getRequest()->getParam('a);
But that is not the best way of doing it as you might accidentally overwrite a parameter a needed parameter.

Zend: Action helper not found

I am trying to create a helper of my own. The Safecheck folder is located in the library folder and contains a Helper folder. The class is called Safecheck_Helper_Authority.php (inside library/Safecheck/Helper).
In Bootstrap.php:
protected function _initHelper()
{
Zend_Controller_Action_HelperBroker::addPrefix('Safecheck_Helper');
}
In Safecheck_Helper_Authority.php:
class Safecheck_Helper_Authority extends Zend_Controller_Action_Helper_Abstract
{
public function hasAuthority($userId, array $ids)
{
}
}
I want to user the functions inside this class. But I get the error "Message: Action Helper by name Authority not found", triggered by the following code:
$this->_helper->authority('hasAuthority');
Maybe I am not calling it with the right code? Am I missing something?
in order to call an action helper in this manner $this->_helper->authority('hasAuthority'); you need to define the direct() method in your helper.
class Safecheck_Helper_Authority extends Zend_Controller_Action_Helper_Abstract
{
public function direct($userId, array $ids)
{
// do helper stuff here
}
}
an easy way to register the helper path and prefix is to use the application.ini:
resources.frontController.actionhelperpaths.Safecheck_Helper = APPLICATION_PATH "/../library/Safecheck/Helper"
to do it in bootstrap (not sure if addPrefix() works with library namespaces):
protected function _initHelper()
{
//addPath(path_to_helper, helper_prefix)
Zend_Controller_Action_HelperBroker::addPath('/../library/Safecheck/Helper', 'Safecheck_Helper');
}
a Simple example of an action helper:
class Controller_Action_Helper_Login extends Zend_Controller_Action_Helper_Abstract
{
//prepares a login form for display
public function direct()
{
$form = new Application_Form_Login();
$form->setAction('/index/login');
return $form;
}
}
Have in your application.ini something similar to
resources.frontController.actionhelperpaths.Application_Action_Helper = APPLICATION_PATH "/../classes/Application/Action/Helper"
The path should be changed to reflect your file path.

Zend Framework: How to inject a controller property from a Zend_Controller_Plugin

I wrote a plugin that needs to set a property on the controller that's currently being dispatched. For example, if my plugin is:
class Application_Plugin_Foo extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
// Get an instance of the current controller and inject the $foo property
// ???->foo = 'foo';
}
}
I want to be able to do this:
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$this->view->foo = $this->foo;
}
}
}
Any help is greatly appreciated!
The action controller is not directly accessible directly from a front-controller plugin. It's the dispatcher that instantiates the controller object and he doesn't appear to save it anywhere accessible.
However, the controller is accessible from any registered action helpers. Since action helpers have a preDispatch hook, you could do your injection there.
So, in library/My/Controller/Helper/Inject.php:
class My_Controller_Helper_Inject extends Zend_Controller_Action_Helper_Abstract
{
public function preDispatch()
{
$controller = $this->getActionController();
$controller->myParamName = 'My param value';
}
}
Then register an instance of the helper in application/Bootstrap.php:
protected function _initControllerInject()
{
Zend_Controller_Action_HelperBroker::addHelper(
new My_Controller_Helper_Inject()
);
}
And, as always, be sure to include My_ as an autoloader namespace in configs/application.ini:
autoloaderNamespaces[] = "My_"
Then, in the controller, access the value directly as a public member variable:
public function myAction()
{
var_dump($this->myParamName);
}
One thing to note: Since the helper uses the preDispatch() hook, I believe it will get called on every action, even an internal forward().
Browsing through the API, I didn't find a way to reach the controller directly (I'm guessing this loop is performed before the controller exists). What I could find is almost as easy to access, albeit with a bit different syntax.
Via request params
class Application_Plugin_Foo extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$yourParam = 'your value';
if($request->getParam('yourParam')) {
// decide if you want to overwrite it, the following assumes that you do not care
$request->setParam('yourParam', $yourParam);
}
}
}
And in a Zend_Controller_Action::xxxAction():
$this->getParam('yourParam');
Via Zend_Controller_Action_Helper_Abstract
There's another way mentioned in MWOP's blog, but it takes the form of an action helper instead: A Simple Resource Injector for ZF Action Controllers. His example would let you access any variable in Zend_Controller_Action as $this->yourParam.