Zend Framework - Passing a variable request in controller - zend-framework

In one of these php frameworks I've noticed a posibility to request the object Request in action as $this->request->paramName
class MyRequest extends Zend_Controller_Request_Http{
public $params = array();
public function __construct() {
$this->params = $this->getParams();
parent::__construct();
}
public function __get($name) {
if (isset($this->_params[$name])) {
return $this->_params[$name];
}
}
public function __isset($name) {
return isset($this->_params[$name]);
}
}
in MyController I've added variable request
public $request = null;
How can I change that standart Request to my one?
public function __construct(
Zend_Controller_Request_Abstract $request,
Zend_Controller_Response_Abstract $response,
array $invokeArgs = array()) {
$request = new MyRequest();
parent::__construct($request, $response, $invokeArgs);
$this->request = $this->getRequest();
}
This function has given no results.
Option 1 is make method _initRequest() in bootstrap:
protected function _initRequest() {
$this->bootstrap ( 'FrontController' );
$front = $this->getResource ( 'FrontController' );
$request = $front->getRequest ();
if (null === $front->getRequest ()) {
$request = new MyRequest();
$front->setRequest ( $request );
}
return $request;
}

A bit dirty and untested solution. Would love to hear if it works.
//Bootstrap:
public function _initRequest()
{
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$front->setRequest(new MyRequest());
}

Try this it might help you:
in controller file
public function exampleAction(){
$result = $this->_request;
$model = new Employer_Model_JobInfo();
$results = $model->sample($result);
}
// the above line stores the values sent from the client side in $result.then sends that values to Model file with parameter $result ..
in model file
class Employer_Model_JobInfo extends Gears_Db_Table_Abstract{
public function sample($param){
$paramVal = $param->getParam('name');
$paramVal1 = $param->getParam('email');
}
}
The name and email are what name used to sent the data from client to server.

Related

Issue with add global variable codeigniter 3

I've admin dashboard with header available in all pages.
in Admin Controller I add function:
`class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view('admin/index');
$this->load->view('admin/includes/_footer');
}
}`
The problem is this working only for "home page (index)" dashboard. When I open anyother page then I get issue undefinied variable.
How can I call this variables in global?
`
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();`
update:
I've one file Core_Controller.php and this file contains:
class Admin_Core_Controller extends Core_Controller
{
public function __construct()
{
parent::__construct();
if (!is_admin()) {
redirect(admin_url() . 'login');
exit();
}
//set control panel lang
$this->control_panel_lang = $this->selected_lang;
if (!empty($this->session->userdata('mds_control_panel_lang'))) {
$this->control_panel_lang = $this->session->userdata('mds_control_panel_lang');
//language translations
$this->language_translations = $this->get_translation_array($this->control_panel_lang->id);
}
//check long cron
if (check_cron_time_long() == true) {
//delete old sessions
$this->settings_model->delete_old_sessions();
//add last update
$this->db->where('id', 1)->update('general_settings', ['last_cron_update_long' => date('Y-m-d H:i:s')]);
}
}
protected function render($view, $data = NULL)
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view($view, $data);
$this->load->view('admin/includes/_footer');
}
public function paginate($url, $total_rows)
{
//initialize pagination
$page = $this->security->xss_clean($this->input->get('page'));
$per_page = $this->input->get('show', true);
$page = clean_number($page);
if (empty($page) || $page <= 0) {
$page = 0;
}
if ($page != 0) {
$page = $page - 1;
}
if (empty($per_page)) {
$per_page = 15;
}
$config['num_links'] = 4;
$config['base_url'] = $url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$config['reuse_query_string'] = true;
$this->pagination->initialize($config);
return array('per_page' => $per_page, 'offset' => $page * $per_page);
}
}
You see I add your code here and now in Admin_Controller I add:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = trans("admin_panel");
$data['order_count'] = $this->order_admin_model->get_all_orders_count();
$data['product_count'] = $this->product_admin_model->get_products_count();
$data['pending_product_count'] = $this->product_admin_model->get_pending_products_count();
$data['blog_posts_count'] = $this->blog_model->get_all_posts_count();
$data['members_count'] = $this->auth_model->get_users_count_by_role('member');
$data['latest_orders'] = $this->order_admin_model->get_orders_limited(15);
$data['latest_pending_products'] = $this->product_admin_model->get_latest_pending_products(15);
$data['latest_products'] = $this->product_admin_model->get_latest_products(15);
$data['latest_reviews'] = $this->review_model->get_latest_reviews(15);
$data['latest_comments'] = $this->comment_model->get_latest_comments(15);
$data['latest_members'] = $this->auth_model->get_latest_members(6);
$data['latest_transactions'] = $this->transaction_model->get_transactions_limited(15);
$data['latest_promoted_transactions'] = $this->transaction_model->get_promoted_transactions_limited(15);
$this->load->view('admin/includes/_header', $data);
$this->render('admin/index');
$this->load->view('admin/includes/_footer');
}
and after this dashboard now working and everytime is refreshed every sec.
I would suggest creating a base controller with a render function, then have your controllers extend from this base controller and use this function to render their pages. The render function can then contain the variables that need to be available on all pages.
Since you already have an Admin_Core_Controller class, you might be able to add the render function there instead (not sure of your project structure). Something like this:
class Admin_Core_Controller // ...
{
// ...
protected function render($view, $data = NULL)
{
$data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
$data['notification'] = $this->order_admin_model->get_all_notifications();
$this->load->view('admin/includes/_header', $data);
$this->load->view($view, $data);
$this->load->view('admin/includes/_footer');
}
}
Then use it to render your page in Admin_Controller:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->render('admin/index');
}
}
Edit Your Admin_Controller class should look like this - I've removed the header and footer includes (those are already rendered by the render function) and passed the $data array to render:
class Admin_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = trans("admin_panel");
$data['order_count'] = $this->order_admin_model->get_all_orders_count();
$data['product_count'] = $this->product_admin_model->get_products_count();
$data['pending_product_count'] = $this->product_admin_model->get_pending_products_count();
$data['blog_posts_count'] = $this->blog_model->get_all_posts_count();
$data['members_count'] = $this->auth_model->get_users_count_by_role('member');
$data['latest_orders'] = $this->order_admin_model->get_orders_limited(15);
$data['latest_pending_products'] = $this->product_admin_model->get_latest_pending_products(15);
$data['latest_products'] = $this->product_admin_model->get_latest_products(15);
$data['latest_reviews'] = $this->review_model->get_latest_reviews(15);
$data['latest_comments'] = $this->comment_model->get_latest_comments(15);
$data['latest_members'] = $this->auth_model->get_latest_members(6);
$data['latest_transactions'] = $this->transaction_model->get_transactions_limited(15);
$data['latest_promoted_transactions'] = $this->transaction_model->get_promoted_transactions_limited(15);
$this->render('admin/index', $data);
}
}

Access $app or $request in Eloquent using Slim Framework

I am building a Slim Framework 4 Api Application, with Eloquent.
public/index.php
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($dbconfig);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$app->add(new RequestUser()); // for calling middleware that adds user
Middlware
class RequestUser
{
public function __invoke(Request $request, RequestHandler $handler): Response
{
....................
$user = User::where('emailid', $email)->first();
$request = $request->withAttribute('user', $user);
$request = $request->withAttribute('token', (string) $exploded_authorization[1]);
return $handler->handle($request);
}
}
Controller
use Psr\Http\Message\ServerRequestInterface as Request;
public function create(Request $request, Response $response, $args)
{
$user = $request->getAttribute('user'); // gives me the request user information
}
Model
<?php
namespace App\Models\TableModel;
use Illuminate\Database\Eloquent\Model;
use DateTime;
use Psr\Http\Message\ServerRequestInterface as Request;
class Details extends Model
{
protected $table = 'my_table';
protected $primaryKey = 'Id';
public $timestamps = false;
protected $fillable = [];
protected $hidden = [];
protected $casts = [
];
protected $appends = ['can_edit', 'can_delete'];
public function getCanEditAttribute(){
$now = date('Y-m-d H:i:s');
return $this->Start_Date >= $now;
}
public function getCanDeleteAttribute(){
//request contains the user information from the middleware? How to access here
return
}
}
I want to access the $request in my Model so that i could get the user information, who is trying to access on CanDelete.
You got the wrong kind of middleware, it needs to be a routing middleware and binded to route or route group directly, not $app->add

Symfony2, Keep form data across redirect

How to use session for retrieving data during redirect? I am getting the error message: "exception 'Symfony\Component\Form\Exception\AlreadySubmittedException' with message 'You cannot change the data of a submitted form."
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Controller\UserController.php
/**
* Creates a new User entity.
*
* #Route("/new", name="user_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($request);
$session = $this->getRequest()->getSession();
$form->setData(unserialize($session->get('userFilter')));
if ( $form->isSubmitted() && $form->isValid() ) {
$session->set( 'userFilter', serialize($form->getData()) );
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
}
return $this->render('MeetingBundle::user/new.html.twig', array(
'user' => $user,
'form' => $form->createView(),
));
} // public function newAction(Request $request)
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\EventListener\ExceptionListener.php
<?php
namespace MeetingBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Router;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
//every time the Kernel throws the kernel.exception event, the function onKernelException() is called.
/* also must create service :
meeting.exception_listener:
class: MeetingBundle\EventListener\ExceptionListener
arguments: [#templating, #kernel, #router]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
*/
class ExceptionListener
{
protected $templating;
protected $kernel;
protected $router;
public function __construct( EngineInterface $templating, $kernel, Router $router)
{
$this->templating = $templating;
$this->kernel = $kernel;
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$request=$event->getRequest();
$referer = $event->getRequest()->headers->get('referer');
$msg="";
$excStr=$exception->__toString(); // returns string finally!
$bdup=strpos( $excStr , 'Integrity constraint violation: 1062 Duplicate entry' );
if($bdup) {
$msg=" This username is already taken. Choose another username. ";
}
if(strlen($msg)!=0) {
// flash messsages are displayed in layout.html
$request->getSession()
->getFlashBag()
->add('Error', $msg);
}
$response = new RedirectResponse($referer); // redirect to the error page
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
$event->setResponse($response);
}
}

Symfony log into by using FosRestBundle

I'm working on a API. To give User Access - for example by smartphone - I need to login users by rest.
Is there an existing module available? Actually, I'm using fosUserBundle. Maybe there is a possibility to get those two bundle work together?
The Users which will login by rest are already existing as "normal" fos users.
It would be grest if you could gomme some links, tips or hints cause I'm searching and searching and searching and for the reason that I am new in symfony it's not that easy :):)
rgrds
I use FOSUserBundle for login since a smartphone by the API.
APIBundle/Controller/UserController.php (the default route is /api)
/**
* #Post("/user/login")
* #Template(engine="serializer")
*/
public function loginAction()
{
$request = $this->get('request');
$username = $request->request->get('username');
$password = $request->request->get('password');
return $this->container->get('myproject_user.user_service')
->login($username, $password);
}
in this method, I call a personal service who manage the user's functions. (UserHandler.php)
UserBundle/Handler/UserHandler.php
class UserHandler implements UserHandlerInterface
{
private $om;
private $entityClass;
private $repository;
private $container;
private $manager;
public function __construct(ObjectManager $om, Container $container, $entityClass)
{
$this->om = $om;
$this->entityClass = $entityClass;
$this->repository = $this->om->getRepository($this->entityClass);
$this->container = $container;
$this->manager = $this->container->get('fos_user.user_manager');
}
public function login($username, $password)
{
$jsonErrorCreator = $this->container->get('myproject_api.create_error_json');
$code = 0;
// check the arguments here.
$user = $this->manager->findUserByUsername($username);
if($user === null) $user = $this->manager->findUserByEmail($username);
if($user === null)
{
$code = 224;
return ($jsonErrorCreator->createErrorJson($code, $username));
}
// check the user password
if($this->checkUserPassword($user, $password) === false)
{
$code = 225;
return ($jsonErrorCreator->createErrorJson($code, null));
}
// log the user
$this->loginUser($user);
$jsonCreator = $this->container->get('myproject_api.create_json');
$response = $jsonCreator->createJson(array('success'=>true, 'user'=>$user));
return $response;
}
protected function loginUser(User $user)
{
$security = $this->container->get('security.context');
$providerKey = $this->container->getParameter('fos_user.firewall_name');
$roles = $user->getRoles();
$token = new UsernamePasswordToken($user, null, $providerKey, $roles);
$security->setToken($token);
}
protected function checkUserPassword(User $user, $password)
{
$factory = $this->container->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
if(!$encoder)
return false;
return $encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt());
}
}
UserBundle/Handler/UserHandlerInterface.php
Interface UserHandlerInterface
{
public function login($username, $password);
}
Don't forget to declare your service !
UserBundle/Resources/config/services.yml
myproject_user.user_service:
class: %myproject_user.user_handler.class%
arguments: [ #doctrine.orm.entity_manager, #service_container, %fos_user.model.user.class%]
You can now login with your smartphone at the adresse api/user/login
I think I got the solution:
http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html
This seems pretty nice to me and paired with Guras inputit should work as well.

zend framework stringtrim filter not working

I'm having trouble with zend framework's string trim filter. I use the following code to set up a text element in a Zend_Form:
$voucherValidator = new Project_Validate_Voucher();
$code = $this->addElement('text', 'code', array('label'=>'Gutscheincode'));
$code = $this->getElement('code')
->addFilter('StringTrim')
->addValidator($voucherValidator, true);
When I type in some text with preceeding blanks or tabs, the validator correctly works on the StringTrim filtered input and accepts the input. When I later check the $_POST['code'] after code submission, I get the unfiltered input. How can I get my text element to post the filtered value?
Use $code = $this->code->getValue() as Zend_Form doesn't actually filter the $_POST array.
Sorry, i know i'm late but in case any one faced the same problem,
I have faced this problem today and i found few ways to solve this problem:
i have answered same reply on this post
Other Post
first my code is:
This is the form class
class Application_Form_UserForm extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setMethod('POST');
$fname = new Zend_Form_Element_Text('fname');
$fname->setLabel('First Name: ');
$fname->setAttribs(Array(
'placeholder'=>'Example: Eslam',
'class'=>'form-control'
));
$fname->setRequired();
$fname->addValidator('StringLength', false, Array(4,20));
$fname->addFilter('StringTrim');
$fname->addFilter('StripTags');
$fname->removeDecorator('DtDdWrapper');
$fname->removeDecorator('label');
$fname->removeDecorator('HtmlTag');
$lname = new Zend_Form_Element_Text('lname');
$lname->setLabel('Last Name: ');
$lname->setAttribs(Array(
'placeholder'=>'Example: Khoga',
'class'=>'form-control'
));
$lname->setRequired();
$lname->addValidator('StringLength', false, Array(4,20));
$lname->addFilter('StringTrim');
$lname->addFilter('StripTags');
$lname->removeDecorator('DtDdWrapper');
$lname->removeDecorator('label');
$lname->removeDecorator('HtmlTag');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email: ');
$email->setAttribs(Array(
'placeholder'=>'Example#Example.com',
'class'=>'form-control'
));
$email->setRequired();
$email->addValidator('StringLength', false, Array(5,250));
$email->addFilter('StringTrim');
$email->addFilter('StripTags');
$email->removeDecorator('DtDdWrapper');
$email->removeDecorator('label');
$email->removeDecorator('HtmlTag');
$gender = new Zend_Form_Element_Select('gender');
$gender->setRequired();
$gender->addMultiOption('male','Male')->
addMultiOption('female','Female')->
addMultiOption('none','Prefer not to mention');
$gender->setAttrib('class', 'form-control');
$track_obj = new Application_Model_Track();
$allTracks = $track_obj->listAll();
$track = new Zend_Form_element_Select('track');
foreach($allTracks as $key=>$value)
{
$track->addMultiOption($value['id'], $value['name']);
}
$submit= new Zend_Form_Element_Submit('submit');
$submit->setAttribs(array('class'=>'btn btn-success'));
$reset= new Zend_Form_Element_Submit('reset');
$reset->setAttribs(array('class'=>'btn btn-danger'));
$this->addElements(array(
$fname,
$lname,
$email,
$gender,
$track,
$submit,
$reset
));
}
}
This is controller class
class UserController extends Zend_Controller_Action{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
}
public function listAction()
{
// action body
$user_model = new Application_Model_User();
$this->view->users = $user_model->listUsers();
$track_form = new Application_Form_Track();
$this->view->track_form = $track_form;
$track_model = new Application_Model_Track();
$request = $this->getRequest();
if($request->isPost())
{
if($track_form->isValid($request->getPost())){
$track_model-> addTrack($request->getParams());
$this->redirect('/user/add');
}
}
}
public function detailsAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user = $user_model->userDetails($us_id);
$trackModel = new Application_Model_Track();
$track = $trackModel->getTrackName($user[0]['track']);
$user[0]['track'] = $track[0]['name'];
$this->view->user = $user[0];
}
public function deleteAction()
{
// action body
$user_model = new Application_Model_User();
$us_id = $this->_request->getParam("uid");
$user_model->deleteUser($us_id);
$this->redirect("/user/list");
}
public function addAction()
{
// action body
$form = new Application_Form_UserForm();
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
/*echo "<pre>";
print_r($form);
echo "</pre>";
exit;*/
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model = new Application_Model_User();
$user_model-> addNewUser($userData);
$this->redirect('/user/list');
}
}
$this->view->user_form = $form;
}
public function editAction()
{
// action body
$form = new Application_Form_UserForm();
$user_model = new Application_Model_User ();
$id = $this->_request->getParam('uid');
$user_data = $user_model-> userDetails($id)[0];
$form->populate($user_data);
$this->view->userName = $user_data['fname']." ".$user_data['lname'];
$this->view->user_form = $form;
$request = $this->getRequest();
if($request->isPost()){
if($form->isValid($request->getPost())){
$userData['fname'] = $form->getValue('fname');
$userData['lname'] = $form->getValue('lname');
$userData['email'] = $form->getValue('email');
$userData['gender'] = $form->getValue('gender');
$userData['track'] = $form->getValue('track');
$user_model-> updateUser($id, $userData);
$this->redirect('/user/list');
}
}
}
}
First Solution:
i used filter on Form elements in the form class,
but i retrieved data from $form object in the controller,
as i found that method
addFilter()
doesn't change in the $_POST array values, so i have retrieved the data from $form object and then passed it as array to Model.
Second Solution:
i have tried to apply the filter on the values in the controller, not in the form by creating object from filter class and apply needed filter
Third Solution:
is to use method
addValidator()
with regex which affects on $_POST values.