How to use monolog in slim 3? - monolog

In my app.php file:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class App extends \DI\Brifge\Slim\app
{
public function configureContainer(ContainerBuilder $builder)
{
$dependencies = [
'logger' => function (Container $container) {
$logger = new Monolog\Logger('logger');
$filename = _DIR__ . '/../log/error.log';
$stream = new Monolog\Handler\StreamHandler($filename, Monolog\Logger::DEBUG);
$fingersCrossed = new Monolog\Handler\FingersCrossedHandler(
$stream, Monolog\Logger::ERROR);
$logger->pushHandler($fingersCrossed);
return $logger;
},
];
}
}
In my custom error handler:
class CustomErrorHandler
{
protected $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $exception)
{
$output = ['success'=>0, 'error'=>"Oops! Something's not right "];
$this->logger->critical($output);
return $response->withStatus(500)
->withHeader('Content-Type', 'application/json')
->write(json_encode($output));
}
}
When an error is thrown, following message is displayed:
Fatal error: Uncaught Error: Class 'App\Monolog\Logger' not found in C:\xampp\htdocs\backend\app\App.php:103 Stack trace: #0 [internal function]: App\App->App{closure}(Object(DI\Container)) #1 C:\xampp\htdocs\backend\vendor\php-di\invoker\src\Invoker.php(82): call_user_func_array(Object(Closure), Array) #2 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Definition\Resolver\FactoryResolver.php(81): Invoker\Invoker->call(Object(Closure), Array) #3 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Definition\Resolver\ResolverDispatcher.php(58): DI\Definition\Resolver\FactoryResolver->resolve(Object(DI\Definition\FactoryDefinition), Array) #4 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Container.php(287): DI\Definition\Resolver\ResolverDispatcher->resolve(Object(DI\Definition\FactoryDefinition), Array) #5 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Container.php(124): DI\Container->resolveDefinition(Object(DI\Definition\FactoryDefinition)) #6 C:\xampp\htdocs\backend\app\App.php(95): DI\Container->get('l in C:\xampp\htdocs\backend\app\App.php on line 103
I have included the statement use Monolog\Logger; in App.php file but I get the above error.

You forgot to register dependencies in configureContainer method:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class App extends \DI\Bridge\Slim\App
{
public function configureContainer(ContainerBuilder $builder)
{
$dependencies = [
'logger' => function (Container $container) {
$logger = new Monolog\Logger('logger');
$filename = _DIR__ . '/../log/error.log';
$stream = new Monolog\Handler\StreamHandler($filename, Monolog\Logger::DEBUG);
$fingersCrossed = new Monolog\Handler\FingersCrossedHandler(
$stream, Monolog\Logger::ERROR);
$logger->pushHandler($fingersCrossed);
return $logger;
},
];
// Register definitions
$builder->addDefinitions($dependencies);
}
}
Also you have a mistake in App class declaration, it's \DI\Bridge\Slim\App, not \DI\Brifge\Slim\app

I understood where I was wrong.
No need to include the lines:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
While instantiating, I have included the complete path.

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);
}
}

Fatal error: Call to a member function selectCollection() on a non-object in \lib\dbconnection.php on line 55

<?php
class DBConnection {
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'lib';
private static $instance;
public $connection;
public $database;
private function _construct()
{
$connectionString = sprintf('mongodb://%s:%d', DBConnection::HOST, DBConnection::PORT);
try {
$this->connection = new Mongo($connectionString); $this->database = $this->connection-> selectDB(DBConnection::DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
}
static public function instantiate()
{
if (!isset(self::$instance)) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public function getCollection($name)
{
return $this->database->selectCollection($name);
}
}
help pleaseee
You have a typo: __construct has two _'s, and you only have one.

Zend Framework - Passing a variable request in controller

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.

Having problems combining Zend_Acl and Zend_Navigation

I have a Federico_Plugin_Acl that extends Zend_Controller_Plugin_Abstract which looks like this:
class Federico_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
private $_acl = null;
private $_auth = null;
const DEFAULT_ROLE = 'guest';
public function __construct($auth) {
$this->_auth = $auth;
$this->_acl = new Zend_Acl();
$this->_acl->addRole(new Zend_Acl_Role(self::DEFAULT_ROLE));
$this->_acl->addRole(new Zend_Acl_Role('user'), self::DEFAULT_ROLE);
$this->_acl->addRole(new Zend_Acl_Role('admin'), 'user');
$this->_acl->addResource(new Zend_Acl_Resource('index'));
$this->_acl->addResource(new Zend_Acl_Resource('users'));
$this->_acl->addResource(new Zend_Acl_Resource('about'));
$this->_acl->addResource(new Zend_Acl_Resource('gisele'));
$this->_acl->addResource(new Zend_Acl_Resource('admin'));
$this->_acl->allow('guest', 'index');
$this->_acl->allow('guest', 'about');
$this->_acl->deny('guest', 'gisele');
$this->_acl->deny('guest', 'users');
$this->_acl->allow('user', 'users', array('index'));
$this->_acl->allow('admin', 'users');
$this->_acl->allow('admin', 'gisele');
}
public function preDispatch(Zend_Controller_Request_Abstract $request) {
if ($this->_auth->hasIdentity()) {
$role = $this->_auth->getStorage()->read()->role;
} else {
$role = self::DEFAULT_ROLE;
}
$action = $request->getActionName();
$controller = $request->getControllerName();
if ($this->_acl->has($controller)) {
if (!$this->_acl->isAllowed($role, $controller, $action)) {
$request->setActionName('login');
$request->setControllerName('index');
}
}
}
}
And this method is in my bootstrap to make use of this class:
protected function _initNavigation()
{
$this->_auth = Zend_Auth::getInstance();
$this->_acl = new Federico_Plugin_Acl($this->_auth);
$this->bootstrap('view');
$view = $this->getResource('view');
$config = new Zend_Config_Xml(APPLICATION_PATH . '/configs/navigation.xml','nav');
$navigation = new Zend_Navigation($config);
$roleAuth = $this->_auth->getIdentity();
if(null == $roleAuth)
$role = 'guest';
else
$role = $roleAuth->role;
$view->navigation($navigation)->setAcl($this->_acl)->setRole($role);
}
With these configurations set like that, I get the following error:
Catchable fatal error: Argument 1 passed to Zend_View_Helper_Navigation_HelperAbstract::setAcl() must be an instance of Zend_Acl, instance of Federico_Plugin_Acl given, called in /home/fiodorovich/public_html/gisele/application/Bootstrap.php on line 118 and defined in /home/fiodorovich/library/ZendFramework/library/Zend/View/Helper/Navigation/HelperAbstract.php on line 333
Call Stack
Which is to be expected since Federico_Plugin_Acl is an instance of Zend_Controller_Plugin_Abstract...Still, if I extend Zend_Acl instead I get this error:
Fatal error: Zend_Acl_Role_Registry_Exception: Role 'guest' not found in /home/fiodorovich/library/ZendFramework/library/Zend/View/Helper/Navigation/HelperAbstract.php on line 522
So...I've been trying for a while to get this thing solved,... but don't seem to get this to work properly...Any ideas on what I'm missing here?
Zend_Controller_Plugin_Abstract and Zend_Acl are completelly different things. What you want to do is get the ACL object out of your plugin (which is now in private section) and pass it over to
$view->navigation($navigation)->setAcl(<here>);

Creating own Zend_Auth_Adapter

i am having difficulties creating my own Zend_Auth_Adapter. i am using Doctrine 2 with it also. so far i have ... code below
i am getting the error
Method "hasIdentity" does not exist and was not trapped in __call()
whats wrong?
use \Doctrine\ORM;
class Application_Auth_Adapter implements Zend_Auth_Adapter_Interface {
private $username;
private $password;
function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
function authenticate() {
$em = Zend_Registry::get('em');
$query = $em->createQuery('select u from Application\Entities\User u WHERE u.name = :username')
->setParameter('username', $this->username);
try {
$user = $query->getSingleResult();
$salt = $user->salt;
$hashedPassword = hash_hmac('sha256', $this->password, $salt);
if ($hashedPassword == $user->password) {
// login success
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
} else {
// wrong password
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, null);
}
} catch (NonUniqueResultException $e) {
// non unique result
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null);
} catch (NoResultException $e) {
// no result found
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, null);
} catch (Exception $e) {
// exception occured
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, null);
}
}
}
UPDATE
i noticed that the problem comes from abt line 123 of Zend_Auth
if ($this->hasIdentity()) {
$this->clearIdentity();
}
but just below that function, authenticate(), its
public function hasIdentity()
i noticed something strange with teh stack trace
#0 [internal function]: Zend_Controller_Action->__call('hasIdentity', Array)
#1 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Auth.php(123): AuthController->hasIdentity()
#2 D:\Projects\Websites\php\ZendFramework\LearningZF\application\controllers\AuthController.php(23): Zend_Auth->authenticate(Object(Application_Auth_Adapter))
#3 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Controller\Action.php(513): AuthController->loginAction()
#4 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('loginAction')
#5 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#6 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#7 D:\ResourceLibrary\Frameworks\ZendFramework\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#8 D:\Projects\Websites\php\ZendFramework\LearningZF\public\index.php(26): Zend_Application->run()
#9 {main}
see AuthController->hasIdentity() its trying to call hasIdentity() from AuthController!
i found out why! see my update ... the stack trace. i am calling a method as if it were static. wont that produce an error? anyways ... i shld be doing
$result = Zend_Auth::getInstance()->authenticate($adapter);
Nice adapter, although I suggest $user->getPassword() and $user->getSalt()