I used Zend Framework version 2. I follow the instruction from here but my project doesn't run well.
Here's my code :
module.config.php
return array(
'controllers'=> array(
'invokables' => array(
'Application\Controller\Index' => 'Application\Controller\IndexController',
),
),
'router' => array(
'routes' => array(
)
),
// Placeholder for console routes
'console' => array(
'router' => array(
'routes' => array(
'list-users' => array(
'options' => array(
'route' => 'show [all|disabled|deleted]:mode users [--verbose|-v]',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'showusers'
)
)
),
),
),
),
);
Module.php
public function getConsoleUsage(Console $console)
{
return array(
'Finding and listing users',
'list [all|disabled] users [-w]' => 'Show a list of users',
'find user [--email=] [--name=]' => 'Attempt to find a user by email or name',
array('[all|disabled]', 'Display all users or only disabled accounts'),
array('--email=EMAIL', 'Email of the user to find'),
array('--name=NAME', 'Full name of the user to find.'),
array('-w', 'Wide output - When listing users use the whole available screen width' ),
'Manipulation of user database:',
'delete user <userEmail> [--verbose|-v] [--quick]' => 'Delete user with email <userEmail>',
'disable user <userEmail> [--verbose|-v]' => 'Disable user with email <userEmail>',
array( '<userEmail>' , 'user email' , 'Full email address of the user to change.' ),
array( '--verbose' , 'verbose mode' , 'Display additional information during processing' ),
array( '--quick' , '"quick" operation' , 'Do not check integrity, just make changes and finish' ),
array( '-v' , 'Same as --verbose' , 'Display additional information during processing' ),
);
}
IndexController.php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
public function indexAction()
{
return new ViewModel();
}
public function showusersAction(){
$request = $this->getRequest();
return "HOLLLLLLLLLLLLAAAAAAAAAAAA"; // show it in the console
}
}
When i tried to run it using command promt :
C:\webserver\www\program\phpcas\zf2-console>php public/index.php show users
Always showing getConsoleUsage() from Module.php, can anyone help me, how to fix it ?
From my (little) experience, it seems that your module.config.php and your Module.php files are correct.
Usually, when I use the console, my controllers are slightly different :
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
// For Cron/Console
use Zend\Console\Request as ConsoleRequest;
use Zend\Console\ColorInterface as Color;
class IndexController extends AbstractActionController
{
public function indexAction()
{
return new ViewModel();
}
public function showusersAction()
{
// Initialize variables.
$request = $this->getRequest();
$console = $this->getServiceLocator()->get('console');
// Make sure that we are running in a console and the user has not tricked our
// application into running this action from a public web server.
if (!$request instanceof ConsoleRequest) {
throw new \RuntimeException('You can only use this action from a console!');
}
// Retrieve values from value flags using their name.
$verbose = (bool)$request->getParam('verbose', false) || (bool)$request->getParam('v', false); // default false
/* ...your other flags... */
/* ...do what you want to do... */
// Let's confirm it works
$console->writeline("Groovy Baby!");
Related
I am using the Herbert Plugin Framework and am creating a plugin.
Here is the code I am using:
panels.php
$panel->add([
'type' => 'panel',
'as' => 'mainPanel',
'title' => 'Plugin',
'rename' => 'General',
'slug' => 'plugin-admin-settings',
'icon' => 'dashicons-chart-area',
'uses' => __NAMESPACE__ . '\Controllers\PluginController#createAdminPage'
]);
Now PluginController
<?php
namespace Plugin\Controllers;
use Herbert\Framework\Models\Option;
use Herbert\Framework\RedirectResponse;
use Herbert\Framework\Http;
use \Google_Client;
use \Google_Service_Analytics;
use Plugin\Helper;
class PluginController {
public static function createAdminPage()
{
$this->option = get_option('pluginAuthenticationSetting');
//if (!isset($this->option['authenticationCode'])):
//if (get_option('pluginAuthenticationSetting') == FALSE):
return view('#Plugin/auth.twig', [
'title' => 'Analytics Reports',
'content' => SELF::settings()
]);
//endif;
}
public static function settings()
{
settings_fields('pluginAuthenticationSetting');
do_settings_sections('pluginAuthenticationSetting');
submit_button();
}
public static function pageInit()
{
wp_register_script(
'plugin',
Helper::assetUrl('/jquery/plugin.js'),
array( 'jquery' )
);
wp_localize_script(
'plugin',
'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ),
'we_value' => 1234 )
);
register_setting(
'pluginAuthenticationSetting',
'plugin_authorization_setting',
array( __CLASS__, 'sanitize' )
);
add_settings_section(
'authenticationSection',
'Authentication Section',
array( __CLASS__, 'printAuthenticationSection' ),
'pluginAuthenticationSetting'
);
add_settings_field(
'authenticationCode',
'Authentication Code',
array( __CLASS__, 'authenticationCodeCallback' ),
'apluginAuthenticationSetting',
'authenticationSection'
);
}
public function sanitization( $input )
{
$new_input = array();
if (isset( $input['authenticationCode']))
$new_input['authenticationCode'] = sanitize_text_field($input['authenticationCode']);
return $new_input;
}
public static function printAuthenticationSection()
{
print 'Enter Your Authentication Code Below:';
}
public static function authenticationCodeCallback()
{
printf( '<input type="text" id="authentication" name="analyticaAuthenticationSetting[authenticationCode]" value="%s" />', isset( $this->option['authenticationCode'] ) ? esc_attr( $this->option['authenticationCode'] ) : '');
}
}
Now pageInit() needs the admin_init hook. If I create a constructor and try like add_action('admin_init', array(__CLASS__, 'pageInit'));, it is not working. If I use it in panel creation and call createAdminPage taht is also not working. How it can be done?
It generates no error, and only the submit button is displayed.
We need to focus on where we want to send data.
Answer: To the administration side of WordPress, that is, we need to use a panel to do the job. When we send data to client side, we use a route.
Here is the code.
Creating a panel
$panel->add([
'type' => 'panel',
'as' => 'mainPanel',
'title' => 'Analytica',
'rename' => 'General',
'slug' => 'analytica-admin-settings',
'icon' => 'dashicons-chart-area',
'uses' => __NAMESPACE__ . '\Controllers\AnalyticaController#index',
'post' => [
// Sending data to save using post.
'save' => __NAMESPACE__ . '\Controllers\AnalyticaController#save',
]
]);
Controller to display the page and save the data in the database
<?php namespace Analytica\Controllers;
use Herbert\Framework\Models\Option;
use Herbert\Framework\RedirectResponse;
use Herbert\Framework\Http;
use Herbert\Framework\Enqueue;
use Herbert\Framework\Notifier;
use \Google_Client;
use Analytica\Helper;
class AnalyticaController {
public function index(){
// Display the form
}
public function save(){
// Validate and save the data
}
}
You need to focus on use Herbert\Framework\Models\Option;. That means there is an model called Option that represents the wp_options table.
Now, what are the functions we use here?
We can use the Laravel Eloquent and Schema here. Now you may understand it; we can do a lot of things here. It is like just we are having some pre-built models and we are working on the same Laravel.
Note: Forget about hooks for some time. We can still suit a theme, but for most of the cases we do not need a theme.
I am trying to learn ZF2 and I just want to specify Javascript and CSS files to be included in my layout. I currently pass an array of paths relative to my public directory to my view and then loop through them. I would like to make use of the built in ZF2 solution using:
$this->headScript();
$this->headStyle();
I have tried many suggested methods on similar questions, but I must not be following them correctly.
One of the solutions I tried which seemed to make sense was here by using either of these in my controller:
$this->getServiceLocator()->get('Zend\View\HelperPluginManager')->get('headLink')->appendStylesheet('/css/style.css');
$this->getServiceLocator()->get('viewhelpermanager')->get('headLink')->appendStylesheet('/css/style.css');
I am not sure what viewhelpermanager it seems like a placeholder the poster used, but I have seen it in more than one question. I went ahead and found the location of Zend\View\HelperPluginManager but that did not work either.
By "not working" I mean my page is displayed without CSS and there is zero output from these:
$this->headScript();
$this->headStyle();
It seems like such a simple task and I do not know why I am having this much of a difficulty.
EDIT #1:
Here is my controller:
<?php
namespace CSAdmin\Controller;
use Zend\View\Model\ViewModel;
use Zend\View\HelperPluginManager;
class LoginController extends AdminController
{
public function __construct() {
parent::__construct();
}
public function indexAction()
{
//Set Action specific Styles and Scripts
$viewHelperManager = $this->getServiceLocator()->get(`ViewHelperManager`);
$headLinkHelper = $viewHelperManager->get('HeadLink');
$headLinkHelper->appendStylesheet('/css/admin/form.css','text/css',array());
$headLinkHelper->appendStylesheet('/css/admin/styles.css','text/css',array());
//Override view to use predefined Admin Views
$view = new ViewModel(array('data'=>$this->data));
$view->setTemplate('CSAdmin/login/login.phtml'); // path to phtml file under view folder
//Set the Admin Layout
$layout = $this->layout();
$layout->setVariable('layout', $this->layoutVars);
$layout->setTemplate('layout/CSAdmin/login.phtml');
//Render Page
return $view;
}
My AdminController:
<?php
namespace CSAdmin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AdminController extends AbstractActionController
{
protected $data = array();
protected $layoutVars = array();
protected $viewHelper;
public function __construct() {
$this->layoutVars['customStyles'] = array();
$this->layoutVars['customScripts'] = array();
$this->layoutVars['miscCode'] = array();
//$this->viewHelper = $viewHelper;
}
}
EDIT #2:
#Wilt Error message for the above to controllers:
Line 19 is
$viewHelperManager = $this->getServiceLocator()->get("ViewHelperManager");
EDIT #3:
There are two modules involved here. Admin and CSAdmin, the controllers from Admin extend the controllers from CSAdmin and all of the controllers from CSAdmin extend a base controller within CSAdmin AdminController. AdminController extends AbstractActionController.
My controller and service_manager arrays for each module.config.php for both modules are below:
Admin:
'service_manager' => array(
'invokables' => array(
'CSAdmin\Form\LoginForm' => 'CSAdmin\Form\LoginForm'
),
'factories' => array(
)
),
'controllers' => array(
'invokables' => array(
),
'factories' => array(
'Admin\Controller\Login' => 'Admin\Factory\LoginControllerFactory',
)
),
// This lines opens the configuration for the RouteManager
'router' => array(
// Open configuration for all possible routes
'routes' => array(
'admin' => array(
'type' => 'literal',
'options' => array(
'route' => '/admin',
'defaults' => array(
'controller' => 'Admin\Controller\Login',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'home' => array(
'type' => 'literal',
'options' => array(
'route' => '/home',
'defaults' => array(
'controller' => 'Admin\Controller\Login',
'action' => 'home'
)
)
),
)
)
)
)
CSAdmin:
'service_manager' => array(
'invokables' => array(
),
'factories' => array(
'CSAdmin\Mapper\LoginMapperInterface' => 'CSAdmin\Factory\LoginMapperFactory',
'CSAdmin\Service\LoginServiceInterface' => 'CSAdmin\Factory\LoginServiceFactory'
)
),
'controllers' => array(
'invokables' => array(
),
'factories' => array(
'CSAdmin\Controller\Admin' => 'CSAdmin\Factory\AdminControllerFactory',
'CSAdmin\Controller\Login' => 'CSAdmin\Factory\LoginControllerFactory',
)
)
EDIT #4:
/module/Admin/src/Admin/Factory/LoginControllerFactory.php:
namespace Admin\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Admin\Controller\LoginController;
use CSAdmin\Service\LoginServiceInterface;
class LoginControllerFactory implements FactoryInterface
{
/**
* Create service
*
* #param ServiceLocatorInterface $serviceLocator
* #return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$realServiceLocator = $serviceLocator->getServiceLocator();
$loginService = $realServiceLocator->get('CSAdmin\Service\LoginServiceInterface');
$loginForm = $realServiceLocator->get('FormElementManager')->get('CSAdmin\Form\LoginForm');
return new LoginController(
$loginService,
$loginForm
);
}
}
/module/CSAdmin/src/CSAdmin/Factory/AdminControllerFactory.php:
namespace CSAdmin\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CSAdmin\Controller\AdminController;
use Zend\View\Helper\BasePath;
class AdminControllerFactory implements FactoryInterface
{
/**
* Create service
*
* #param ServiceLocatorInterface $serviceLocator
* #return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$realServiceLocator = $serviceLocator->getServiceLocator();
//$viewHelper = $realServiceLocator->get('Zend\View\Helper\BasePath');
//return new AdminController($viewHelper);
return new AdminController();
}
}
/module/CSAdmin/src/CSAdmin/Factory/LoginControllerFactory.php:
namespace CSAdmin\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CSAdmin\Controller\LoginController;
class LoginControllerFactory implements FactoryInterface
{
/**
* Create service
*
* #param ServiceLocatorInterface $serviceLocator
* #return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$realServiceLocator = $serviceLocator->getServiceLocator();
$loginService = $realServiceLocator->get('CSAdmin\Service\LoginServiceInterface');
$loginForm = $realServiceLocator->get('FormElementManager')->get('CSAdmin\Form\LoginForm');
return new LoginController(
$loginService,
$loginForm
);
}
}
EDIT #5:
After correcting the type of quotes being used I am still not getting the stylesheets in my layout. As a test I change ->appendStylesheet() to ->someMethod() and it properly reports that the method does not exist. So it definitely has an instance of the HeadLink object. As a next step I decided to just try defining everything in the layout file and it still does not use the stylesheets. See below for the exact code used in the <head> tag of my layout file.
<?php echo $this->doctype(); ?>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $this->layout['title']; ?></title> //Intend to change eventually.
<?php
$this->headLink()->appendStylesheet('/css/admin/form.css');
$this->headLink()->appendStylesheet('/css/admin/styles.css');
echo $this->headScript();
echo $this->headStyle(); //This outputs nothing when viewing with the chrome debugger.
</head>
EDIT #6:
In order to get it to work, instead of using:
echo $this->headScript();
echo $this->headStyle();
I just had to do:
echo $this->headLink();
You will have to add echo to output the result...
echo $this->headScript();
echo $this->headStyle();
echo $this->headLink();
UPDATE
To get the Zend\View\HelperPluginManager in your controller you can do like this:
$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
Then you can do:
$headLinkHelper = $viewHelperManager->get('headLink');
UPDATE 2
Another thing, but it is a bit ridiculous, no wonder it was hard to find.
You used wrong quotes:
`ViewHelperManager` //You cannot use these: `
Try like this:
'ViewHelperManager'
or like this:
"ViewHelperManager"
you need to append file in this way
$this->headScript()->appendFile(
'/js/prototype.js',
'text/javascript',
array('conditional' => 'lt IE 7')
);
then you write it
echo $this->headScript();
note echo head script is required only one time. otherwise you inser js more time
more info at
http://framework.zend.com/manual/current/en/modules/zend.view.helpers.head-script.html
I'm attempting to create a custom filter and inject it into a service via factory.
use Zend\InputFilter\InputFilter;
class WSRequestFilter extends InputFilter{
protected $inputFilter;
public function init(){
$this->add( array(
'name' => 'apiVersion',
'required' => true,
'filters' => [
array('name' => 'Real'),
...
In Module.php...
public function getServiceConfig(){
return array(
...
'factories' => array(
'Puma\Service\WebServiceLayer' => function($sm) {
$wsRequestFilter = new Filter\WSRequestFilter();
$wsRequestFilter->init();
$wsl = new Service\WebServiceLayer($wsRequestFilter);
return $wsl;
},
),
);
}
But I get service not found exception when executing $wsRequestFilter->init();. I have also tried to initialize the filter using the InputFilterManager similar to here but I got a service not found trying to access the manager via $serviceManager->get('InputFilterManager'). I think I am missing something fundamental here.
The init() method invoked automatically by InputFilterManager just after the filter object created. You don't need to invoke manually.
Add this to your module configuration:
'input_filters' => array(
'invokables' => array(
'ws-request-filter' => '\YourModule\Filter\WSRequestFilter',
),
),
And change your service factory like below:
public function getServiceConfig(){
return array(
...
'factories' => array(
'Puma\Service\WebServiceLayer' => function($sm) {
$filter = $sm->get('InputfilterManager')->get('ws-request-filter')
$wsl = new \YourModule\Service\WebServiceLayer($filter);
return $wsl;
},
),
);
}
It should work.
I've got a problem. I'm using zfcuser in my project, and now i want to create profile pages. I'have created the showAction() in UserController, but when i put the url to webbrowser, i will got 404.
public function showAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('zfcuser', array(
'action' => 'register'
));
}
try {
$user = $this->zfcUserAuthentication()->getIdentity()->getUser($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('zfcuser', array(
'action' => 'register'
));
}
return new ViewModel(array(
'user' => $user));
}
I also created custom function to get User info all in one row.
It looks like this:
public function getUser($id){
$rowset = $this->tableGateway->select(array('user_id' => $id));
$row = $rowset->current();
return $row;
}
And it is in Entity/User.php
This is my showAction() in zfc UserController.php
I thought its wrong module.config, but its not working anyway. I changed my module.config to this:
'show' => array(
'type' => 'Literal',
'options' => array(
'route' => '/show[/][:id]',
'defaults' => array(
'controller' => 'zfcuser',
'action' => 'show',
),
),
),
My problem is, i can not even get to url to show this controller action.
Where can be problem. I want to make simple user profile page.
The problem is in my opinion your route 'Literal'. A literal route can't have params.
You have to use Segment instead
But it's not the only problem i think.
ZfcUser comes with a packaging, profile page already exist :
Take a look to this complete slideshare :
Zf2 Zfc-User
I have application created in Zend Framework 2. I would like to run controller action as cron job. I read a lot about it but I don't know how to run it.
I did something like that. I added console route to module's module.config.php
'console' => array(
'router' => array(
'routes' => array(
'cronroute' => array(
'options' => array(
'route' => 'updateproducts',
'defaults' => array(
'controller' => 'Application\Controller\Console',
'action' => 'update'
)
)
)
),
),
),
I created Controller named ConsoleController
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model;
use Application\Model\Auth;
class ConsoleController extends AbstractActionController
{
protected $usersTable = null;
public function updateAction()
{
$this->getUsersTable()->cronTest();
return false;
}
public function getUsersTable()
{
if (!$this->usersTable) {
$sm = $this->getServiceLocator();
$this->usersTable = $sm->get('Application\Model\UsersTable');
}
return $this->usersTable;
}
Inside Auth.php
public function cronTest(){
$data = array(
'login' => 'cronZend'
);
$this->tableGateway->insert($data);
}
I think that everything here is OK and I tried to write something inside command line on shared server:
/usr/local/bin/php /home/****/domains/****/public_html/public/index.php updateproducts
and it doesn't work. When I test it writing something like that in cron.php
$dbc = mysqli_connect(****);
$query = "INSERT INTO vm_user (login) VALUES ('cron')";
mysqli_query($dbc, $query);
and in command line
/usr/local/bin/php /home/****/domains/****/public_html/cron.php
it works fine. Could anyone tell me what is wrong or how to do it?