How to call a custom service on the service locator object from Module#getViewHelperConfig() in Zend Framewok 2? - module

I have a ViewHelper and want to initialize it in Module#getViewHelperConfig():
<?php
namespace Search;
use statements...
class Module implements
ConfigProviderInterface,
ServiceProviderInterface,
AutoloaderProviderInterface,
ViewHelperProviderInterface {
public function getConfig() ...
public function getAutoloaderConfig() ...
public function getServiceConfig() {
$breakpoint = null;
try {
return array (
'factories' => array(
...
'SearchFormCourseSearchForm' => function ($serviceManager) {
$cacheService = $serviceManager->get('Cache\Model\CityStorage');
$cities = $cacheService->getCities();
$searchForm = new Form\CourseSearchForm($cities);
return $searchForm;
},
)
);
} ...
}
public function getViewHelperConfig() {
$breakpoint = null;
return array(
'factories' => array(
'searhForm' => function($serviceManager) {
$helper = new View\Helper\SearchForm(array('render' => true, 'redirect' => false));
$helper->setViewTemplate('search/search/search-courses');
$searchForm = $serviceManager->get('SearchFormCourseSearchForm');
$helper->setSearchForm($searchForm);
return $helper;
}
)
);
}
But ZF doesn't call my factory. Instead of this it tries to create a new SearchFormCourseSearchForm instance:
Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for SearchFormCourseSearchForm' in /var/www/bar/foo/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 456
How should I use service factories got from Module#getServiceConfig() creating a ViewHelper in Module#getViewHelperConfig()?

You need to get the main service locator. The $serviceManager in getViewHelperConfig() is the View Helper service locator.
To get the main service locator in your getViewHelperConfig() function, do the following:
$maimSm = $serviceManager->getServiceLocator();
Therefore:
public function getViewHelperConfig() {
return array(
'factories' => array(
'searhForm' => function($serviceManager) {
$helper = new View\Helper\SearchForm(array('render' => true, 'redirect' => false));
$helper->setViewTemplate('search/search/search-courses');
$maimSm = $serviceManager->getServiceLocator();
$searchForm = $maimSm->get('SearchFormCourseSearchForm');
$helper->setSearchForm($searchForm);
return $helper;
}
)
);
}
There are quite a few posts explaining this strategy in a bit more details, I'll go hunt for them.
Edit
See Using Zend Framework service managers in your application for a nice description of service managers/locators in ZF2.

Related

Laravel 9 error route | The GET method is not supported

I am having a problem fetching a list of certain customers (authenticated users) via API. When I use this route in Postman I receive the following error.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:
The GET method is not supported for this route. Supported methods:
POST. in file
D:\api\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php
on line 118
api.php
Route::post('/register', [UserAuthController::class, 'register']);
Route::post('/login', [UserAuthController::class, 'login'])
->name('login');
Route::apiResource('/customer', CustomerController::class)
->middleware('auth:api');
Controller
class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return response([ 'customers' =>
CustomerResource::collection($customers),
'message' => 'Successful'], 200);
}
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'first_name'=>'required|max:120',
'email'=>'required|email|unique:users',
'password'=>'required|min:6'
]);
if($validator->fails()){
return response(['error' => $validator->errors(),
'Validation Error']);
}
$customer = Customer::create($data);
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function show(Customer $customer)
{
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function update(Request $request, Customer $customer)
{
$customer->update($request->all());
return response([ 'employee' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function destroy(Customer $customer)
{
$customer->delete();
return response(['message' => 'Customer deleted']);
}
}
I solved this problem by adding Accept|json/application in headers of Postman.

Symfony 3.3 CraueFormFlowBundle Request_stack is empty

my first question to this site is a little difficult to describe.
I am quite new to Symfony, startet with 3.2 and updated recently to 3.3.5 (not sure if relevant for the problem).
I tried to use CraueFormFlowBundle (multistep form bundle) but cannot get it to work.
The problem is that trying to access the flow results in an exception:
Error: Call to a member function getCurrentRequest() on null
Symfony\Component\Debug\Exception\ FatalErrorException
in vendor/craue/formflow-bundle/Form/FormFlow.php (line 191)
Line 191 shows: $currentRequest = $this->requestStack->getCurrentRequest();
Modifying the FormFlow.php with dump line shows that $this->requestStack is null.
I have not enough knowledge about this bundle to know where to start looking for the problem.
The flow definition is based on the location example:
namespace EngineeringBundle\Form;
use Craue\FormFlowBundle\Form\FormFlow;
use Craue\FormFlowBundle\Form\FormFlowInterface;
class SelectExaminationFlow extends FormFlow
{
/**
* {#inheritDoc}
*/
protected function loadStepsConfig()
{
dump("loadStepsConfig");
return array(
array(
'label' => 'engineering.discipline',
'form_type' => new SelectExaminationStep1Form(),
),
array(
'label' => 'engineering.date',
'form_type' => new SelectExaminationStep2Form(),
'skip' => function($estimatedCurrentStepNumber, FormFlowInterface $flow) {
return $estimatedCurrentStepNumber > 1 && !$flow->getFormData()->canHaveRegion();
},
),
array(
'label' => 'confirmation',
),
);
}
The form definition is also quite simple and works without problems:
class SelectExaminationStep1Form extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
dump("buildForm");
$builder
->add('id', HiddenType::class)
->add('discipline', EntityType::class, array(
'class' => 'EngineeringBundle:Discipline',
'choice_label' => 'disciplineName',
'label' => 'engineering.discipline.label'
)
);
}
public function getName() {
return $this->getBlockPrefix();
}
public function getBlockPrefix() {
return 'createEngineeringStep1';
}
}
services.yml:
EngineeringBundle\Form\SelectExaminationFlow:
parent: craue.form.flow
autowire: false
autoconfigure: false
public: true
engineering.form_flow:
alias: EngineeringBundle\Form\SelectExaminationFlow
public: true
Controller:
/**
* #Route("create", name="engineering_create")
*/
public function createAction()
{
return $this->processFlow(new ExaminationDate(), $this->get('engineering.form_flow'));
}
Thanks in advance
Sebastian
I was having the same problem, resolved it by adding a constructor to vendor/craue/formflow-bundle/Form/FormFlow.php with the following content:
public function __construct(RequestStack $requestStack, FormFactoryInterface $formFactory, DataManagerInterface $dataManager, EventDispatcherInterface $eventDispatcher) {
$this->formFactory = $formFactory;
$this->requestStack = $requestStack;
$this->dataManager = $dataManager;
$this->eventDispatcher = $eventDispatcher;
}
Make sure to place it after all setter-methods. Problem seems to be related to a symfony update.

ZF2 testing - mock object ignored by serviceManager

I'm trying to run tests on my controller in Zend Framework 2.3.
My tested action looks like this:
public function listAction() {
// optional filtering
$filter = $this->params('filter'); // filter type
// params from JSON
$jsonPost = $this->getRequest()->getContent();
$params = json_decode($jsonPost);
$param1 = isset($params->query1) ? $params->query1 : NULL;
$param2 = isset($params->query2) ? $params->query2 : NULL;
$json = Array( // json container
'status' => TRUE,
'data' => Array(),
);
try {
// get data from Model
$list = new Mapping\Books\Listing();
if( !empty($filter)) { // optional filtering
$list->addFilter($filter, $param1, $param2);
}
$data = $list->setOrder()->getList();
// final data mapping to JSON and formating
foreach($data as $isbn => $book) {
$json['data'][$isbn] = Array(
'ISBN' => $book->getISBN(),
'title' => $book->getTitle(),
'rating' => $book->getRating(),
'release_date' => $book->getReleaseDate()->format('F Y'),
'authors' => Array() // multiple
);
// final authors mapping
foreach($book->getAuthors() as $author) {
$json['data'][$isbn]['authors'][] = Array(
'author_id' => $author->getId(),
'author_name' => $author->getName()
);
}
}
} catch(Exception $e) {
$json = Array(
'status' => FALSE,
'error' => $e->getMessage()
);
}
return new JsonModel( $json );
}
My testing method looks like this:
public function testListActionWithoutParams()
{
// object mocking
$listingMock = $this->getMockBuilder('Books\Model\Mapping\Books\Listing')
->disableOriginalConstructor()
->setMethods(Array('getData', 'setOrder'))
->getMock();
$listingMock->expects($this->once())->method('setOrder')
->will($this->returnSelf());
$listingMock->expects($this->once())->method('getData')
->willReturn( Array() ); // for testing is enough
$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Books\Model\Mapping\Books\Listing', $listingMock);
// dispatch
$this->dispatch('/books');
// routing tests
$this->assertResponseStatusCode(200);
$this->assertModuleName('Books');
$this->assertControllerName('Books\Controller\Index');
$this->assertControllerClass('IndexController');
$this->assertActionName('list');
$this->assertMatchedRouteName('list');
// header tests
$this->assertResponseHeaderContains('Content-type', 'application/json; charset=utf-8');
}
I think I'm missunderstanding something here. My understanding is, that serviceManager will also "notify" autoloader, that actually called class should be replaced by mock object, but it does not.
How can I replace my object with mocked, please ?
Firstly you controller have a lot of logic, what is incorrect.
Secondly, I can give you only workflow of the code:
In your controller you need a method with will be returning list object, so in line:
// get data from Model
$list = new Mapping\Books\Listing();
should be new method call:
// get data from Model
$list = $this->getListing();
And the method:
public function getListing()
{
return new Mapping\Books\Listing();
}
Now you need to mock this method in the controller. And object returned by the mocked method should be your mocked Mapping\Books\Listing object.

Using Multiple Database Connection Not Working For Extension

I am doing multiple database connection using the tutorial at http://www.yiiframework.com/wiki/544/multiple-database-connection-select-database-based-on-login-user-id-dynamic/ . The code is working fine in the model. But the problem is I am using an extension where I am using db connection using Yii::app()->db; Here I am getting exception Property "CWebApplication.dbadvert" is not defined. The controller of the extension is extended from CExtController. Please help.
In the example you're referring dbadvert is set up for custom active record class RActiveRecord, not for the web application.
If you want to use it like Yii::app()->dbadvert, you would need to set it up in components section of your config.php like this
'dbadvert' => array(
'class' => 'CDbConnection'
*params here*
),
UPD
You can create a wrapper component for CDbConnection, that will change the connection string any way you want and put in as a webapp component.
<?php
class CMultiuserDatabaseConnection extends CApplicationComponent {
public function __call($name, $params) {
$db = $this->db;
return call_user_func_array(($db, $name), $params);
}
public $dbConnectionClass = 'CDbConnection';
public $connections = null;
public $defaultConfiguration = null;
public function getDatabaseConfiguration($user) {
if (!$this->connections) { return array(); }
return array_key_exists($user, $this->connections) ? $this->connections[$user] : $this->defaultConfiguration;
}
public function getDb() {
$user = Yii::app()->user;
if ($user->isGuest) { return false; }
$username = $user->name;
$config = $this->getDatabaseConfiguration($username);
if (!$config) { return false; }
$dsn = array_key_exists('dsn', $config) ? $config['dsn'] : null;
if (!$dsn) { return false; }
$user = array_key_exists('user', $config) ? $config['user'] : null;
$password = array_key_exists('password', $config) ? $config['password'] : null;
$result = new $this->dbConnectionClass($dsn, $user, $password);
return $result;
}
}
That's a crude example of component, which you can set up as your 'db' component and then you'll get 'connections' option for storing the per-user configuration in that way:
'components' => array(
...
'db' => array(
'class' => "CMultiuserDatabaseConnection",
'connections' => array(
"first-user-name" => array(
// just another db configuration here, for user-one
),
"second-user-name" => array(
// just another db configuration herer, for user two
),
...
),
'defaultConfiguration' => array(
/*
* here goes configuration for all other user, that were not specified
* in connections.
*/
),
),
...
),
I wrote the query for the extension in a model as functions. and in the CExtController created an instance of the model. Then I called those functions and everything is working fine.

call model in zend form using dependencies + zend framework 2

I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.