Zend framework: how to pass creation options to services - zend-framework

When registering a service in module.config.php like
'service_manager' => [
'factories' => [
\Path\To\Your\Service\AService => \Path\To\Your\Service\Factory\AServiceFactory,
]
]
I can't pass in creation options when calling the service factory neither in ZF2 (when the factory implements MutableCreationOptionsInterface) nor in ZF3 (via $container->get(\Path\To\Your\Service\AService::class, $options).
Could anyone tell me how to pass the creation options to the services?

MutableOptions is currently only available on plugin manager instances; the service manager does not implement it. This is why you see the discrepancy.
Références : https://github.com/zendframework/zend-servicemanager/issues/7
Sample : https://samsonasik.wordpress.com/2014/08/14/zend-framework-2-using-creationoptions-in-pluginmanager/
COMPLEMENT
My solution is to add a method with a fluent pattern to the AService class :
class AService
{
public function __construct(...)
{
//your code, you can inject variables from $container by AServiceFactory
}
public function setOptions($options)
{
// your setting from $options
...
// fluent pattern
return $this;
}
}
To use your service :
$container->get(\Path\To\Your\Service\Aservice::class)->setOptions($options);

Related

Cakephp 3.x Crud plugin beforeFind event not available

I have a Cakephp 3.x API using CRUD plugin.
This is my crud configuration:
$this->loadComponent('Crud.Crud', [
'actions' => [
'Crud.Index',
'Crud.View',
'Crud.Add',
'Crud.Edit',
'Crud.Delete'
],
'listeners' => [
'Crud.Api',
'Crud.ApiPagination',
'Crud.ApiQueryLog'
]
]);
In my controller when I call this->Crud->implementedEvents() it returns beforeFilter startuperxot beforePaginate only
public function index(){
$this->Crud->implementedEvents(); //returns beforeFilter startuperxot beforePaginate
$this->Crud->on('beforeFind', function(\Cake\Event\Event $event) {
if(isset($this->request->query['state'])){
$event->getSubject()->query->where(['state =' => $this->request->query['state']]);
}
});
return $this->Crud->execute();
}
How can I enable beforeFind listener? Thanks in advance.
You should use beforePaginate on index
https://crud.readthedocs.io/en/latest/actions/index.html#crud-beforepaginate

signup to Laravel from a different server

I want to show a signup form on a website but then when user hits submit, the form data will be posted to a Laravel app (on a different server) for registration.
So far, laravel stops it throwing the CSRF not found exception. Any idea how to work around it ?
If both applications are yours?
You can create a new middleware group:
protected $middlewareGroups = [
'web' => [
...
],
'remote-login' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Commenting/removing/disabling the VerifyCsrfToken middleware. Then map it to a new file:
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::middleware('remote-login')
->namespace($this->namespace)
->group(base_path('routes/remote-login.php'));
}
Then in your routes/remote-login.php, you better create a non-trivial login route:
Route::group(['prefix' => 'remote-login'], function () {
Route::get('/auth/8g7h6jk5l4oA/', function () {
dd('do you authentication');
});
});
Antonio's approach will work, but it's easier to just add the routes you don't want protected by the CSRF middleware to the $except array in app/Http/Middleware/VerifyCsrfToken.php.

How to make POST call using FOSRestBundle

I am trying to setup a RESTFUL web service using FOSRestBunble, but I have some problem making POST calls, here's my setup:
app/config/routing.yml
rest:
type: rest
resource: "routing_rest.yml"
prefix: /api
app/config/routing_rest.yml
Rest_User:
type: rest
resource: "#AppBundle/Resources/config/routing_rest.yml"
AppBundle/Resources/config/routing_rest.yml
rest_application:
type: rest
resource: "AppBundle:Rest"
name_prefix: api_
AppBundle/Controller/RestController.php
class RestController extends FOSRestController
{
public function testrestAction(Request $request)
{
$r = [
'is' => 'TEST'
];
return $r;
}
public function getArticleAction()
{
$r = [
'is' => 'GET'
];
return $r;
}
public function postArticleAction()
{
$r = [
'is' => 'POST'
];
return $r;
}
}
I also made PUT and DELETE test methods. so when I do some test call
GET /api/testrest
{
"is": "TEST"
}
GET /api/article
{
"is": "GET"
}
POST /api/article
No route found for "POST /api/article": Method Not Allowed (Allow: GET, HEAD) (405 Method Not Allowed)
PUT and DELETE are also fine. Am I missing some configuration?
second problem: if I make a API folder inside Controller folder, I change the namespace for RestController to "namespace AppBundle\Controller\API;" and I update "AppBundle/Resources/config/routing_rest.yml" to
resource: "AppBundle:API:Rest"
then I got this message:
Can't locate "AppBundle:API:Rest" controller in /var/www/ws/app/config/routing_rest.yml (which is being imported from "/var/www/ws/app/config/routing.yml").
any help appreciated
1-option, run app/console debug:router (or bin/console debug:router if v > 2.8), to list generated routes;
2-option, add RouteResource annotation to class (eg. article), rename postArticleAction to postAction and check POST /api/articles is responding or not;
3-option, add article url explicitly with #POST annotation, eg. /** #Post("article") */

Symfony upgrading 2.1 FOSUserBundle custom registration form Exception

My custom registration form was working well with the version 1.2.* but when i update symfony in 2.1 and FOSUserBundle in 2.0.*, I've got this problem that I don't know how to resolve.
The error :
The type name specified for the service "kairos_user.registration_form_type" does not match the actual name. Expected "kairos_user_registration", given "fos_user_registration"
My service definition :
services:
kairos_user.registration_form_type:
class: Kairos\UserBundle\Form\Type\RegistrationFormType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: kairos_user_registration }
And my config.yml
fos_user:
db_driver: orm #cf kairos doctrine admin
firewall_name: main
user_class: Kairos\UserBundle\Entity\User
registration:
form:
type: kairos_user_registration
The alias of your registration form service must match the name returned by your registration form type class. In Kairos\UserBundle\Form\Type\RegistrationFormType try to change the return value of getName() method
class RegistrationFormType extends AbstractType
{
// ...
public function getName()
{
return 'kairos_user_registration';
}
}

How to dispatch url with subdomain in Zend PHPUnit Controller test?

I want to test my controller which works on subdomain www.username.domain.com
The problem is when I dispatch in ControllerTestCase it throws Zend_Controller_Dispatcher_Exception
routes.php:
$userRouter = new Zend_Controller_Router_Route_Hostname(':user.domain.com'));
$router->addRoute('user', $userRouter->chain(new Zend_Controller_Router_Route('',
array('controller' => 'user'))));
UserControllerTest:
require_once 'AbstarctControllerTestCase.php';
class UserControllerTest extends AbstarctControllerTestCase
{
public function setUp()
{
$this->cleardb();
parent::setUp();
}
public function testRoute()
{
$this->dispatch('www.username.domain.com');
$this->assertController('user');
}
}
AbstarctControllerTestCase:
abstract class AbstarctControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap()
{
chdir(dirname(dirname(dirname(dirname(__FILE__)))));
require 'application/test/controllerunit/routes.php';
Zend_Session::start();
}
(...)
}
Result:
PHPUnit 3.3.17 by Sebastian Bergmann.
F
Time: 1 second
There was 1 failure:
1) testRoute(UserControllerTest)
Failed asserting last controller used was "user"
When I dispatch normal URI like /login it work well but the problem is dispatching URLs with hostnames.
Any ideas?
Thank you all.
Did you try setting the $_SERVER variable in setup?
e.g.
$_SERVER['SERVER_NAME'] = 'www.username.domain.com';
and then call dispatch as per usual.
See - http://php.net/manual/en/reserved.variables.server.php
Define $_SERVER['HTTP_HOST'] before calling dispatch() .
There is already a ticket with the same concern under http://framework.zend.com/issues/browse/ZF-11680