Can the process of creating an module in zf2 be shortend? - php

I am looking at a few tutorials and to just create 1 module you have to modify a bunch of configuration files in order to make the controllers, models, and views work. I see this as impossible to try and remember it all or comprehend what it is I’m doing. Is there an alternative method that creates these for me? so that i don’t have to write it all out every time i create a controller, or a module etc. I honestly don’t see how this is faster. I come from a codeigniter background so making this switch has me banging my head against the wall multiple times trying to comprehend.

I've been using ZF2 for a few months now, and I've found that writing a class to generate that config for you is helpful.
There is no tool out there to do that for you. But if you follow the following approach, you should come right quite quickly:
class Configurator {
public static function route($name, $url, $controller, $action='index') {
return array(
'router' => array(
...
),
);
}
# Other static configuring methods
...
}
Then in your config you use the Configurator like this:
use Configurator;
return array_merge_recursive(
array(
'view_manager' => array(
...
),
),
# Other top-level config
...
Configurator::route('home', '/', 'Application\Controller\Index'),
Configurator::route('other', '/other', 'Application\Controller\Other')
);
Your config is deep-merged by array_merge_recursive, utimately producing the config you want with your own custom-built generators. You're at liberty to configure whole sets of config with one method, so you can create a resource configurator which sets up the controller invokables, the routes, and anything else required in one method.
array_merge_recursive FTW!
Enjoy! :)

Related

ZF2 view plugin manager not merging config

On my module.config.php I've got something like:
return [
'view_helpers' => [
'invokables' => [
'mycustomviewhelper' => 'Namespace\View\Helper\MyCustomViewHelper',
],
],
];
I have also got a utility class that will handle the responsibility of rendering a helper. Something like Zend\Paginator.
Zend\Paginator has a __toString() method that proxies to render() call, which instantiates View\Renderer\PhpRenderer() and then calls $view->paginationControl($this).
I am trying to replicate the similar functionality in my utility class, which has similar strategy to what Zend\Paginator already does, the only thing being different is my view helper is a custom one. Hence, my code looks like:
$view->MyCustomViewHelper($this);
This does not work, because the PhpRenderer ignores the config defined manually and does the following in getHelperPluginManager:
$this->setHelperPluginManager(new HelperPluginManager());
I've tried invoking the helpers already defined in ViewHelperManager and this works well.
I did try merging in the config beforehand and then setting the PhpRenderer in the view but then this caused other problems, such as my partials were not found etc.
Now my question is why does ZF not consider any custom registered views when trying to render it in isolation. Is there any other way to do this?
Thank you.
Right, after a bit of a debugging, and playing with the configs, I was able to make this work. Still not sure if this is the best way to do this, but looks like currently there's no other way to make it work.
I created a factory for the utility class, instantiated the PhpRenderer, and then merged in my config with the ViewPluginManager manually. My factory now looks like:
public function createService(ServiceLocatorInterface $serviceLocatorInterface)
{
$dataTable = new DataTable;
$phpRenderer = new PhpRenderer();
$config = new \Zend\ServiceManager\Config([
'invokables' => [
'datatablerenderer' => 'DataTable\View\Helper\DataTableRenderer'
],
]);
$phpRenderer->setHelperPluginManager(new HelperPluginManager($config));
$dataTable->setView($phpRenderer);
return $dataTable;
}
However will have to refactor this so that the config comes from the view_helpers config key and is not hardcoded.

Phalcon router doesn't react to subfolders and namespace declaration

So I've been reading a ton of stackoverflow and phalcon forum threads.. (I'm starting to hate this framework), but nothing seem to work and it doesn't explain why like Laravel does, for example.
I'm just trying to be able to operate with this application structure:
As you can see, all I want is to use namespaced controllers in subfolders to make more order for my code.
According to all explanations, here's my loader.php:
<?php
$loader = new \Phalcon\Loader();
/**
* We're a registering a set of directories taken from the configuration file
*/
$loader->registerDirs(
array(
$config->application->controllersDir,
$config->application->modelsDir,
$config->application->pluginsDir
)
)->register();
AFAIK, Phalcon should traverse all subfolders for not found classes when used via registerDirs.
Then I define my routes to specific controller after the main route to index controllers in base directory:
<?php
$router = new Phalcon\Mvc\Router(false);
$router->add('/:controller/:action/:params', array(
'namespace' => 'App\Controllers',
'controller' => 1,
'action' => 2,
'params' => 3,
));
$router->add('/:controller', array(
'namespace' => 'App\Controllers',
'controller' => 1
));
$router->add('/soccer/soccer/:controller', array(
'namespace' => 'App\Controllers\Soccer',
'controller' => 1
));
$router->add('/soccer/:controller/:action/:params', array(
'namespace' => 'App\Controllers\Soccer',
'controller' => 1,
'action' => 2,
'params' => 3
));
return $router;
And one of my controllers look like:
<?php namespace App\Controllers\Soccer;
use App\Controllers\ControllerBase as ControllerBase;
class IndexController extends ControllerBase
{
public function indexAction()
{
}
}
What's wrong here? Default top namespace is not registered? Am I missing something?
This just doesn't work. When I try to open myserver.com/soccer which I expect to go to app/controllers/soccer/IndexController.php, but instead it tells me:
SoccerController handler class cannot be loaded
Which basically means it's looking for SoccerController.php in /controllers directory and totally ignores my subfolder definition and routes.
Phalcon 1.3.0
Stuck on this for a week. Any help - Much appreciated.
I was having a problem with loading the ControllerBase and the rest of the controllers in the controllers folder using namespaces. I was having a hard time since other example projects worked fine and I realized that I was missing a small detail in the despatcher declaration where I was supposed to setDefaultNamespace
(ref: https://github.com/phalcon/vokuro/blob/master/app/config/services.php)
$di->set('dispatcher', function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace('App\Controllers');
return $dispatcher;
});
or you can specify it directly on the routing declaration file like this
$router->add("/some-controler", array(
'namespace' => 'App\Controllers'
'controller' => 'some',
'action' => 'index'
));
that should work as well, it might be a bit confusing at first with namespaces but once you get a hang of it you will love this extremely fast framework
It looks like your namespaces have capitals
App\Controllers\Soccer
and your folder structure does not
app\controllers\soccer
In my app I have controllers with a namespace and I have just tried changing the case of the folders so they don't match and I get the missing class error.
Of course it does raise a question, how many controllers are you planning on having that namespacing them is worthwhile? Are you grouping controllers and action by function or content? I used to have loads of controllers in Zend, but now I have grouped them by function I only have 16 and I am much happier. e.g. I suspect soccer, rugby, hockey etc will probably be able to share a sport controller, articles, league positions etc will have a lot of data in common.
ps Don't give up on Phalcon! In my experience it is sooo much faster than any other PHP framework I have used it is worth putting up with a lot :)
Are you sure Phalcon traverses subfolders when registering directories to the autoloader? Have you tried adding a line to your autoloader which explicitly loads the controllers\soccer directory?
Alternatively, if your soccer controller is namespaced, you can also register the namespace: "App\Controllers\Soccer" => "controllers/soccer/" with the autoloader.

CMS Routing in MVC

I am creating my own MVC framework in php as a means to learn more advanced programming. I've got the framework up and running however I have an issue regarding the current routing method. I want the framework to support a backend cms to compliment the front end website. The issue is that my routing structure works like so - mywebsite.com/controller/method/id
The routing engine sorts the information into an array like this
segments 0 => controller, 1 => method, 2 => id
Right now if I visit mywebsite.com/projects it takes me to what I have set up as an admin page. Not only do I want this to be accessible only from mywebsite.com/admin/projects, I want the mywebsite.com/projects to take me to frontend.
So if I want to visit mywebsite.com/projects I'd like it to render the "front" controller, pushing "projects" into the method. If I visit mywebsite.com/admin/projects I'd like it to load the projects controller.
Here's the current routing class in whole as follows.
<?php
class Request {
//url domain.com/controller/method/other
//holds url segments 0 => controller, 1 => method, 2 => other, etc
public $segments;
function __construct() {
$this->parse_globals();
}
function parse_globals(){
//$uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));
$uri = (empty($_GET['rt'])) ? '' : $_GET['rt'];
$this->segments = array_filter(explode('/', $uri));
if (in_array("admin", $this->segments)) {
array_shift($this->segments);
}
print_r($this->segments);
//remove index php
if( reset($this->segments) == 'index.php') {
array_shift ($this->segments);
}
}
function controller(){
return $this->segment(0);
}
function method(){
return $this->segment(1);
}
function param( $str ){
return isset($_REQUEST[$str]) ? $_REQUEST[$str] : false;
}
function segment( $no ){
return isset($this->segments[$no]) ? $this->segments[$no] : false;
}
}
Instead of simply using explode() to separate the segments of URL, you could use a set of regular expression pattern.
For example, this following patter would try to match at firsts action, and, if action exists them check if there is controller set before it:
'/(:?(:?\/(?P<controller>[^\/\.,;?\n]+))?\/(?P<action>[^\/\.,;?\n]+))?/'
Most of PHP frameworks use different ways to generate such patterns, with simplified notations. This way you can set which parts for each pattern are mandatory and which optional. And it is also possible to provide fallback values for the optional parts.
That said ...
Before starting to make something so complicated as cms with framework, you might invest some additional time in researching OOP. I would recommend to at least watch lectures from Miško Hevery and Robert C. Martin. Just because you think, that you know how to write a class, does not mean, that you understands object oriented programming.
Update
I have listed few materials in this answer. You might find them useful,
Additionally here are two more lectures, that were not in answer above:
Clean Code I: Arguments
Clean Code III: Functions
My understanding is that there's three routing cases:
The basic one:
/<controller>/<action>/<parameters>
A special one for the admin panel (where "admin" would be a kind of separate module):
/<module>/<controller>/<action>/<parameters>
And finally a special case for "/projects" which maps to "/front/projects".
In that case, you need to make your routing class more flexible so that it can handle any kind of routing scheme. In a framework like Kohana, this would be done with rules such as:
Route::set('adminModule', 'admin/projects')
->defaults(array(
'controller' => 'projects',
'action' => 'admin',
));
Route::set('projectPage', 'projects')
->defaults(array(
'controller' => 'front',
'action' => 'projects',
));
Route::set('default', '(<controller>(/<id>(/<action>)))')
->defaults(array(
'controller' => 'index',
'action' => 'index',
));
Obviously this is just an example but you get the idea. Basically, you want to provide some sensible default routing (eg. controller/action/id) but you also need to allow users to configure other routes.
I am currently developing a php router which is targeted at extreme high performance. you probably might want to take a look.
https://github.com/c9s/Pux
We also provide a pattern compiler that is doing the same thing as yours. but you can write a simpler path instead of complex patterns.
e.g., you may write something like this:
/product/:id/:name [ id => '\d+', name => '\w+' ]
FYI:
Pux is 48.5x faster than symfony router in static route dispatching, 31x faster in regular expression dispatching. (with pux extension installed)
Pux tries not to consume computation time to build all routes dynamically (like Symfony/Routing). Instead, Pux compiles your routes to plain PHP array for caching, the compiled routes can be loaded from cache very fast.
With Pux PHP Extension support, you may load and dispatch the routes 1.5~2x faster than pure PHP Pux.

Make friendly url in zend framework

I have built a site on zend-framework 1.9.7. I want to make friendly url for every page which has a URL similar to this : http://mysite/search/detail/id/124
I want the friendly URL to look like: http://mysite/search/detail/ram
Where "ram" is the name of user which has id=124
I have include RewriteRule ^name/(.*)/$ guid/$1 in .htaccess file, but it doesn't work.
I suggest you to take a look at the Zend Controller Quickstart which walks through the steps of setting up the standard routing (which already provides everything for nice URLs).
If you want more detailed Info on the Routing, then I suggest to take a look at Zend_Controller_Router's Manual.
Specifically I would handle your case through a Router Route, for example:
<?php
$router = Zend_Controller_Front::getInstance()->getRouter();
$detailsRoute = new Zend_Controller_Router_Route("search/detail/:name", array(
'controller' => 'search',
'action' => 'detail'
));
$router->addRoute('searchDetail', $detailsRoute);
The part :name is a parameter which gets filled with the value ram of you desired URL, and can be retrieved with $request->getParam('name'); later on.
Controllers in ZF have the functionality to be called from custom routes. You can find the documentation here. They give you a wide variety of options to choose the kind of route you want to use. It can be pretty URLs like those in blogs or even REST endpoints.
You don't have to mess with the htaccess file for this as all calls to non-static resources are directed through index.php anyway.
have a zend plugin that works very well for this.
<?php
/** dependencies **/
require 'Zend/Loader/Autoloader.php';
require 'Zag/Filter/CharConvert.php';
Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true);
//filter
$filter = new Zag_Filter_CharConvert(array(
'replaceWhiteSpace' => '-',
'locale' => 'en_US',
'charset'=> 'UTF-8'
));
echo $filter->filter('ééé ááá 90');//eee-aaa-90
echo $filter->filter('óóó 10aáééé');//ooo-10aaeee
the plugin is super easy to use.
hug!

PHP Application URL Routing

So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on)
I want to make this framework, and the apps it has use a Resource Oriented Architecture.
Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.
I prefer to use reg ex over making my own format since it is common knowledge. I wrote a small class that I use which allows me to nest these reg ex routing tables. I use to use something similar that was implemented by inheritance but it didn't need inheritance so I rewrote it.
I do a reg ex on a key and map to my own control string. Take the below example. I visit /api/related/joe and my router class creates a new object ApiController and calls it's method relatedDocuments(array('tags' => 'joe'));
// the 12 strips the subdirectory my app is running in
$index = urldecode(substr($_SERVER["REQUEST_URI"], 12));
Route::process($index, array(
"#^api/related/(.*)$#Di" => "ApiController/relatedDocuments/tags",
"#^thread/(.*)/post$#Di" => "ThreadController/post/title",
"#^thread/(.*)/reply$#Di" => "ThreadController/reply/title",
"#^thread/(.*)$#Di" => "ThreadController/thread/title",
"#^ajax/tag/(.*)/(.*)$#Di" => "TagController/add/id/tags",
"#^ajax/reply/(.*)/post$#Di"=> "ThreadController/ajaxPost/id",
"#^ajax/reply/(.*)$#Di" => "ArticleController/newReply/id",
"#^ajax/toggle/(.*)$#Di" => "ApiController/toggle/toggle",
"#^$#Di" => "HomeController",
));
In order to keep errors down and simplicity up you can subdivide your table. This way you can put the routing table into the class that it controls. Taking the above example you can combine the three thread calls into a single one.
Route::process($index, array(
"#^api/related/(.*)$#Di" => "ApiController/relatedDocuments/tags",
"#^thread/(.*)$#Di" => "ThreadController/route/uri",
"#^ajax/tag/(.*)/(.*)$#Di" => "TagController/add/id/tags",
"#^ajax/reply/(.*)/post$#Di"=> "ThreadController/ajaxPost/id",
"#^ajax/reply/(.*)$#Di" => "ArticleController/newReply/id",
"#^ajax/toggle/(.*)$#Di" => "ApiController/toggle/toggle",
"#^$#Di" => "HomeController",
));
Then you define ThreadController::route to be like this.
function route($args) {
Route::process($args['uri'], array(
"#^(.*)/post$#Di" => "ThreadController/post/title",
"#^(.*)/reply$#Di" => "ThreadController/reply/title",
"#^(.*)$#Di" => "ThreadController/thread/title",
));
}
Also you can define whatever defaults you want for your routing string on the right. Just don't forget to document them or you will confuse people. I'm currently calling index if you don't include a function name on the right. Here is my current code. You may want to change it to handle errors how you like and or default actions.
Yet another framework? -- anyway...
The trick is with routing is to pass it all over to your routing controller.
You'd probably want to use something similar to what I've documented here:
http://www.hm2k.com/posts/friendly-urls
The second solution allows you to use URLs similar to Zend Framework.
Use a list of Regexs to match which object I should be using
For example
^/users/[\w-]+/bookmarks/(.+)/$
^/users/[\w-]+/bookmarks/$
^/users/[\w-]+/$
Pros: Nice and simple, lets me define routes directly
Cons: Would have to be ordered, not making it easy to add new things in (very error prone)
This is, afaik, how Django does it
I think a lot of frameworks use a combination of Apache's mod_rewrite and a front controller. With mod_rewrite, you can turn a URL like this: /people/get/3 into this:
index.php?controller=people&method=get&id=3. Index.php would implement your front controller which routes the page request based on the parameters given.
As you might expect, there are a lot of ways to do it.
For example, in Slim Framework , an example of the routing engine may be the folllowing (based on the pattern ${OBJECT}->${REQUEST METHOD}(${PATTERM}, ${CALLBACK}) ):
$app->get("/Home", function() {
print('Welcome to the home page');
}
$app->get('/Profile/:memberName', function($memberName) {
print( 'I\'m viewing ' . $memberName . '\'s profile.' );
}
$app->post('/ContactUs', function() {
print( 'This action will be fired only if a POST request will occure');
}
So, the initialized instance ($app) gets a method per request method (e.g. get, post, put, delete etc.) and gets a route as the first parameter and callback as the second.
The route can get tokens - which is "variable" that will change at runtime based on some data (such as member name, article id, organization location name or whatever - you know, just like in every routing controller).
Personally, I do like this way but I don't think it will be flexible enough for an advanced framework.
Since I'm working currently with ZF and Yii, I do have an example of a router I've created as part of a framework to a company I'm working for:
The route engine is based on regex (similar to #gradbot's one) but got a two-way conversation, so if a client of yours can't run mod_rewrite (in Apache) or add rewrite rules on his or her server, he or she can still use the traditional URLs with query string.
The file contains an array, each of it, each item is similar to this example:
$_FURLTEMPLATES['login'] = array(
'i' => array( // Input - how the router parse an incomming path into query string params
'pattern' => '#Members/Login/?#i',
'matches' => array( 'Application' => 'Members', 'Module' => 'Login' ),
),
'o' => array( // Output - how the router parse a query string into a route
'#Application=Members(&|&)Module=Login/?#' => 'Members/Login/'
)
);
You can also use more complex combinations, such as:
$_FURLTEMPLATES['article'] = array(
'i' => array(
'pattern' => '#CMS/Articles/([\d]+)/?#i',
'matches' => array( 'Application' => "CMS",
'Module' => 'Articles',
'Sector' => 'showArticle',
'ArticleID' => '$1' ),
),
'o' => array(
'#Application=CMS(&|&)Module=Articles(&|&)Sector=showArticle(&|&)ArticleID=([\d]+)#' => 'CMS/Articles/$4'
)
);
The bottom line, as I think, is that the possibilities are endless, it just depend on how complex you wish your framework to be and what you wish to do with it.
If it is, for example, just intended to be a web service or simple website wrapper - just go with Slim framework's style of writing - very easy and good-looking code.
However, if you wish to develop complex sites using it, I think regex is the solution.
Good luck! :)
You should check out Pux https://github.com/c9s/Pux
Here is the synopsis
<?php
require 'vendor/autoload.php'; // use PCRE patterns you need Pux\PatternCompiler class.
use Pux\Executor;
class ProductController {
public function listAction() {
return 'product list';
}
public function itemAction($id) {
return "product $id";
}
}
$mux = new Pux\Mux;
$mux->any('/product', ['ProductController','listAction']);
$mux->get('/product/:id', ['ProductController','itemAction'] , [
'require' => [ 'id' => '\d+', ],
'default' => [ 'id' => '1', ]
]);
$mux->post('/product/:id', ['ProductController','updateAction'] , [
'require' => [ 'id' => '\d+', ],
'default' => [ 'id' => '1', ]
]);
$mux->delete('/product/:id', ['ProductController','deleteAction'] , [
'require' => [ 'id' => '\d+', ],
'default' => [ 'id' => '1', ]
]);
$route = $mux->dispatch('/product/1');
Executor::execute($route);
Zend's MVC framework by default uses a structure like
/router/controller/action/key1/value1/key2/value2
where router is the router file (mapped via mod_rewrite, controller is from a controller action handler which is defined by a class that derives from Zend_Controller_Action and action references a method in the controller, named actionAction. The key/value pairs can go in any order and are available to the action method as an associative array.
I've used something similar in the past in my own code, and so far it's worked fairly well.
Try taking look at MVC pattern.
Zend Framework uses it for example, but also CakePHP, CodeIgniter, ...
Me personally don't like the MVC model, but it's most of the time implemented as "View for web" component.
The decision pretty much depends on preference...

Categories