Slim PHP access object in route group - slim

hello I want to create an object that can be used inside all the nested routes
use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
return function (App $app) {
$app->group('/api', function (App $app) {
$this->user = \User::findOrFail(1);
$app->get('/profile', function ($request, $response, $args) {
var_dump($this->user);
});
});
};
the error I´m getting is
Type: Slim\Exception\ContainerValueNotFoundException
Message: Identifier "user" is not defined.

for that you should use a container
$app = new \Slim\App();
$container = $app->getContainer();
$container['user'] = function () {
//code
};

Related

Using Scopes on the Load method not working

Is there a way to abstract this Closure to my MerchantUser model in a way similar to using scopes on with()?
So far I have this which works:
$merchant_user->load(['permissions' => function ($query) use ($merchantId) {
if ($merchantId) {
$query->where('merchant_user_permission.merchant_id','=', $merchantId);
}
}]);
But I'd like to do something like this:
$merchant_user->loadPermissions($merchantId);
In my Model:
public function scopeLoadPermissions($query, $merchantId = null)
{
return $query->load(['permissions' => function ($q) use ($merchantId) {
if ($merchantId) {
$q->where('merchant_user_permission.merchant_id','=', $merchantId);
}
}]);
}
Which at the moment just returns an error:
"Method Illuminate\Database\Query\Builder::load does not exist."
For this case you dont need add scope. Instead if you can add this function in your model
public function loadPermissions($merchantId = null)
{
return $this->load(['permissions' => function ($q) use ($merchantId) {
if ($merchantId) {
$q->where('merchant_user_permission.merchant_id','=', $merchantId);
}
}]);
}
and usage
$merchant_user->loadPermissions($merchantId);

typeahead it just returning letter by letter

I want to make an autocomplete search box, when I try to realize an search it is returning me letter by letter instead of word by words. it also is returning me one value from db when I have two values. I am using typeahead.min.js from bootstrap. why is this happening?
controller
public function search(){
$search = $this->input->post('search');
$query = $this->products->search($search);
$data = array();
foreach ($query as $key => $value) {
$this->json($value);
}
}
model
public function search($data){
$this->db->like('description',$data,'both');
$query = $this->db->get('storelte_products');
return $query->result_array();
}
ajax
$('#search').typeahead({
source: function (query,process) {
$.ajax({
url: URL_SEARCH_PRODUCT,
type: 'POST',
data: {query: query},
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
process(data.description);
}
});
}
});
json
{"id":"4165","provider_id":"1005","hash_id":"a7f0d2b95c60161b3f3c82f764b1d1c9","code":"BCBF-BE6A","description":"ajg","purchase_price":"7.00","sale_price":"77.00","wholesale_price":"7.00","min_stock":"7","stock":"7","max_stock":"7","created_at":"2017-04-09 22:21:28","status":"1"}

Slim 3 - How to add 404 Template?

In Slim 2, I can over write the default 404 page easily,
// #ref: http://help.slimframework.com/discussions/problems/4400-templatespath-doesnt-change
$app->notFound(function () use ($app) {
$view = $app->view();
$view->setTemplatesDirectory('./public/template/');
$app->render('404.html');
});
But in Slim 3,
// ref: http://www.slimframework.com/docs/handlers/not-found.html
//Override the default Not Found Handler
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'text/html')
->write('Page not found');
};
};
How can I add my 404 template ('404.html') in?
Create your container:
// Create container
$container = new \Slim\Container;
// Register component on container
$container['view'] = function ($c) {
$view = new \Slim\Views\Twig('./public/template/');
$view->addExtension(new \Slim\Views\TwigExtension(
$c['router'],
$c['request']->getUri()
));
return $view;
};
//Override the default Not Found Handler
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['view']->render($response->withStatus(404), '404.html', [
"myMagic" => "Let's roll"
]);
};
};
Construct the \Slim\App object using the $container and run:
$app = new \Slim\App($container);
$app->run();
Option 1:
use Twig (or any other templating engine)
Option 2:
$notFoundPage = file_get_contents($path_to_404_html);
$response->write($notFoundPage);

Phalcon MongoDb save

I have problem with save method of collections in Phalcon.It doesn't work and doesn't give me any errors or something.I want to create a Micro App with mongoDb:
Phalcon version: 1.3.4
php : 5.5.9
Here are the registered services:
<?php
use Phalcon\DI\FactoryDefault,
Phalcon\Assets\Manager as AssetsManager,
Phalcon\Mvc\Collection\Manager as CollectionManager,
Phalcon\Mvc\View\Simple as View,
Phalcon\Mvc\View\Engine\Volt,
Phalcon\Mvc\Url as UrlResolver,
Phalcon\Flash\Session as Flash,
Phalcon\Flash\Direct as FlashDirect,
Phalcon\Session\Adapter\Files as Session;
$di = new FactoryDefault();
$di['url'] = function () {
$url = new UrlResolver();
$url->setBaseUri('/dasshy/');
return $url;
};
/**
* Flash service with custom CSS classes
*/
$di['flash'] = function () {
return new Flash(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
};
/**
* Flash service with custom CSS classes
*/
$di['flashDirect'] = function () {
return new FlashDirect(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
};
$di['session'] = function () {
$session = new Session(array(
'uniqueId' => 'dasshy-'
));
$session->start();
return $session;
};
$di['mongo'] = function () {
$mongo = new MongoClient();
return $mongo->selectDb("stats");
};
$di->set('collectionManager', function () {
return new Phalcon\Mvc\Collection\Manager();
});
I want to use the ODM, so here is the model Collection:
<?php
namespace Dasshy\Models;
class Messages extends \Phalcon\Mvc\Collection
{
public $content;
public $senderId;
public $receiverId;
public $date;
}
And here how i use it at handlers.php:
<?php
use Dasshy\Models\Messages;
use Phalcon\Mvc\Micro\Collection;
$app->map('/send/{receiverId}/{senderId}/{content}', function ($receiverId, $senderId, $content) use ($app) {
$messageModel = new Messages();
$messageModel->receiverId = $receiverId;
$messageModel->senderId = $senderId;
$messageModel->content = $content;
$messageModel->date = date('Y-m-d H-i-s', time());
$messageModel->save();
if ($messageModel->save() == false) {
echo "Umh, We can't store robots right now: \n";
foreach ($messageModel->getMessages() as $message) {
echo $message, "\n";
}
} else {
echo "Great, a new robot was saved successfully!";
}
});
$app->map('/messages', function () use ($app) {
var_dump(Messages::find());
exit;
});
you need to setup the mongo connection on the service...
$config = $di->getShared('config')->mongo;
$connect_data = $config->username . ':' . $config->password . '#' . $config->host . ':' . $config->port . '/' . $config->dbname;
$mongo = new \MongoClient("mongodb://" . $connect_data);
return $mongo->selectDB($config->dbname);
...since you are not connecting to any mongo server

Zend application jQuery ajax call getting error

I am trying to work with jQuery in Zend Framework. And the use case I am facing problem is when I am trying to save data to the db. Always receiving ajax error though the data is being saved in the database.
The controller that I am using to add data is like below:
public function addAction()
{
// action body
$form = new Application_Form_Costs();
$form->submit->setLabel('Add');
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
{
if ($form->isValid($formData))
{
$costTitle = $this->_request->getPost('costTitle');
$costAmount = $this->_request->getPost('costAmount');
$costs = new Application_Model_DbTable_Costs();
if($costs->addCosts($costTitle, $costAmount))
{
echo "suces";
}
// $this->_helper->redirector('index');
}
else
{
$form->populate($formData);
}
}
}
}
And the jQuery that is passing data is as follows:
$('#cost').submit(function (){
data = {
"cost_title":"cost_title",
"cost_amount":"cost_amount"
};
$.ajax({
dataType: 'json',
url: '/index/add',
type: 'POST',
data: data,
success: function (response) {
alert(response);
},
timeout: 13*60*1000,
error: function(){
alert("error!");
}
});
});
I am getting always error.
What is the problem in this code?
Thanks in advance.
I would strongly recommend you implement the newest Zend/AJAX methods.
// Inside your php controller
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('add', 'json')
->initContext();
}
public function addAction()
{
// action body
$form = new Application_Form_Costs();
$form->submit->setLabel('Add');
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
{
if ($form->isValid($formData))
{
$costTitle = $this->_request->getPost('costTitle');
$costAmount = $this->_request->getPost('costAmount');
$costs = new Application_Model_DbTable_Costs();
if($costs->addCosts($costTitle, $costAmount))
{
// The view variables are returned as JSON.
$this->view->success = "success";
}
}
else
{
$form->populate($formData);
}
}
}
// Inside your javascript file
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get("/index/add/format/json", function(data) {
alert(data);
})
.error(function() { alert("error"); });
For more information:
AjaxContext (ctrl+f)
jQuery.get()
I think you are getting an error on Session output. Why don't you disable the view-renderer, since you just need an answer for the request echo "suces" which is more than enough for your AJAX.