Adding new view/phtml file in Zend Framework2 - php

I would like to add a new phtml file to my index folder in which I already have several views:
index
landing
And so on... I access them by using the following logic:
sitename.com/index/landing
or
sitename.com/index/index
How can I add the phtml file (my new view) to my index folder so that I'm able to see it when I enter in the browser:
sitename.com/index/mynewview
I'm quite new to the whole Zend Framework, and I'm not sure how the structure works exactly, so I'd like to find out more. Can you guys help me out with this, how am I supposed to do this?
Thanks heaps! :)
P.S. The views are in the following directory structure:
module/application/view/application/index/
and then here are all of the views, this is where I'd like to add my new view and access it from browser like this:
/index/testview
Edit:
When I add the testview.phtml to the index directory and put some test tags like this in it:
<h1> Testing new view page </h1>
It's not being rendered on the browser

Because this is an MVC framework, you're skipping a few steps. You're probably going to get a few harsh responses, but I'll try to fill in the holes for you very quickly.
Ignore the file folder structure for a minute.
This is a route:
/index/landing
Routes point to Actions inside of Controllers to work.
Assuming you have started with the skeleton, open up your module's module.config.php, you should see route config, e.g.:
https://github.com/zendframework/ZendSkeletonApplication/blob/master/module/Application/config/module.config.php#L29
You'll need to add a config entry for the routes you want to serve. It could be as simple as a Literal entry for /index/landing, or something more complex (Segments, Regex, etc.) that handle patterns for routing. Spend some time tinkering and learning here; routes are pretty critical to working with MVC.
When configuring the route, the assumption is that you have a Controller set up, and that this Controller has an Action (to which your route is pointed). That Action, is where you can connect template files (phtml,twig,etc.) to routes:
// dummy action that serves index/testview
public function fooAction(){
$vm = new Zend\View\Model\ViewModel();
$vm->setTemplate('index/testview');
return $vm;
}
That index/testview, will be in your module's view templates, not in your public folder.
I think that's a reasonable primer to get you on your way!
Take some time to learn:
http://zf2.readthedocs.io/en/latest/index.html#userguide
Maybe start here:
http://zf2.readthedocs.io/en/latest/in-depth-guide/understanding-routing.html
ZF2 (V3 is coming!) is a beautiful thing, it's worth it.
Good luck.

Related

Dealing with Views in Phalcon Controllers

I am working on a newly created Phalcon project, and I don't really know how to actually use multiples views.
What is the entry point? I don't really know when each method in the controller is called, under which conditions, etc.
Where is the control flow defined? is it based in the name of the view? or is there a place where you can register them?
Phalcon is a bit different than other well-known PHP frameworks, in that not much is pre-configured or pre-built by default. It's quite loosely-coupled. So you have to decide where and how your control flow will work. This means that you will need to dig deeper in the documentation and also that there could be different way to achieve the same thing.
I'm going to walk you through a simple example and provide references, so you can understand it more.
1) You would start by defining a bootstrap file (or files) that will define the routes, or entry points, and will setup and create the application. This bootstrap file could be called by an index.php file that is the default file served by the web server. Here is an example of how such bootstrap file will define the routes or entry points (note: these are just fragments and do not represent all the things that a bootstrap file should do):
use Phalcon\Di\FactoryDefault;
// initializes the dependency injector of Phalcon framework
$injector = new FactoryDefault();
// defines the routes
$injector->setShared('router', function () {
return require_once('some/path/routes.php');
});
Then it the routes.php file:
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;
// instantiates the router
$router = new Router(false);
// defines routes for the 'users' controller
$user_routes = new RouterGroup(['controller' => 'users']);
$user_routes->setPrefix('/users');
$user_routes->addGet('/show/{id:[0-9]{1,9}}', ['action' => 'show']);
$router->mount($user_routes);
return $router;
Im defining routes in an alternate way, by defining routes groups. I find it to be more easy to organize routes by resource or controller.
2) When you enter the url example.com/users/show/123, the routes above will match this to the controller users and action show. This is specified by the chunks of code ['controller' => 'users'], setPrefix('/users') and '/show/{id:[0-9]{1,9}}', ['action' => 'show']
3) So now you create the controller. You create a file in, let's say, controllers/UsersController.php. And then you create its action; note the name that you used in the route (show) and the suffix of Action:
public function showAction(int $id) {
// ... do all you need to do...
// fetch data
$user = UserModel::findFirst(blah blah);
// pass data to view
$this->view->setVar('user', $user);
// Phalcon automatically calls the view; from the manual:
/*
Phalcon automatically passes the execution to the view component as soon as a particular
controller has completed its cycle. The view component will look in the views folder for
a folder named as the same name of the last controller executed and then for a file named
as the last action executed.
*/
// but in case you would need to specify a different one
$this->view->render('users', 'another_view');
}
There is much more stuff related to views; consult the manual.
Note that you will need to register such controller in the bootstrap file like (Im also including examples on how to register other things):
use Phalcon\Loader;
// registers namespaces and other classes
$loader = new Loader();
$loader->registerNamespaces([
'MyNameSpace\Controllers' => 'path/controllers/',
'MyNameSpace\Models' => 'path/models/',
'MyNameSpace\Views' => 'path/views/'
]);
$loader->register();
4) You will also need to register a few things for the views. In the bootstrap file
use Phalcon\Mvc\View;
$injector->setShared('view', function () {
$view = new View();
$view->setViewsDir('path/views/');
return $view;
});
And this, together with other things you will need to do, particularly in the bootstrap process, will get you started in sending requests to the controller and action/view defined in the routes.
Those were basic examples. There is much more that you will need to learn, because I only gave you a few pieces to get you started. So here are some links that can explain more. Remember, there are several different ways to achieve the same thing in Phalcon.
Bootstrapping:
https://docs.phalconphp.com/en/3.2/di
https://docs.phalconphp.com/en/3.2/loader
https://docs.phalconphp.com/en/3.2/dispatcher
Routing: https://docs.phalconphp.com/en/3.2/routing
Controllers: https://docs.phalconphp.com/en/3.2/controllers
More on Views (from registering to passing data to them, to templating and more): https://docs.phalconphp.com/en/3.2/views
And a simple tutorial to teach you some basic things: https://docs.phalconphp.com/en/3.2/tutorial-rest
The application begins with the routing stage. From there you grab the controller and action from the router, and feed it to the dispatcher. You set the view then call the execute the dispatcher so it access your controller's action. From there you create a new response object and set its contents equal to the view requests, and finally send the response to the client's browser -- both the content and the headers. It's a good idea to do this through Phalcon rather than echoing directly or using PHP's header(), so it's only done at the moment you call $response->send(); This is best practice because it allows you to create tests, such as in phpunit, so you can test for the existence of headers, or content, while moving off to the next response and header without actually sending anything so you can test stuff. Same idea with exit; in code, is best to avoid so you can write tests and move on to the next test without your tests aborting on the first test due to the existence of exit.
As far as how the Phalcon application works, and in what steps, it's much easier to follow the flow by looking at manual bootstrapping:
https://docs.phalconphp.com/en/3.2/application#manual-bootstrapping
At the heart of Phalcon is the DI, the Dependency Injection container. This allows you to create services, and store them on the DI so services can access each other. You can create your own services and store them under your own name on the DI, there's nothing special about the names used. However depending on the areas of Phalcon you used, certain services on the DI are assumed like "db" for interacting with your database. Note services can be set as either shared or not shared on the DI. Shared means it implements singleton and keeps the object alive for all calls afterwards. If you use getShared, it does a similar thing even if it wasn't initially a shared service. The getShared method is considered bad practice and the Phalcon team is talking about removing the method in future Phalcon versions. Please rely on setShared instead.
Regarding multiple views, you can start with $this->view->disable(); from within the controller. This allows you to disable a view so you don't get any content generated to begin with from within a controller so you can follow how views work from within controllers.
Phalcon assumes every controller has a matching view under /someController/someView followed by whatever extension you registered on the view, which defaults to .volt but can also be set to use .phtml or .php.
These two correspond to:
Phalcon\Mvc\View\Engine\Php and Phalcon\Mvc\View\Engine\Volt
Note that you DON'T specify the extension when looking for a template to render, Phalcon adds this for you
Phalcon also uses a root view template index.volt, if it exists, for all interactions with the view so you can use things like the same doctype for all responses, making your life easier.
Phalcon also offers you partials, so from within a view you can render a partial like breadcrumbs, or a header or footer which you'd otherwise be copy-pasting into each template. This allows you to manage all pages from the same template so you're not repeating yourself.
As far as which view class you use within Phalcon, there's two main choices:
Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
While similar, Phalcon\Mvc\View gives you a multiple level hierarchy as described before with a main template, and a controller-action based template as well as some other fancy features. As far as Phalcon\Mvc\View\Simple, it's much more lightweight and is a single level.
You should be familiar with hierarchical rendering:
https://docs.phalconphp.com/en/3.2/views#hierarchical-rendering
The idea is with Phalcon\Mvc\View that you have a Main Layout (if this template exists) usually stored in /views/index.volt, which is used on every page so you can toss in your doctypes, the title (which you would set with a variable the view passed in), etc. You'd have a Controller Layout, which would be stored under /views/layouts.myController.volt and used for every action within a controller (if this template exists), finally you'd have the Action Layout which is used for the specific action of the controller in /views/myController/myAction.volt.
There are all types of ways you can break from Phalcon's default behavior. You can do the earlier stated $this->view->disable(); so you can do everything manually yourself so Phalcon doesn't assume anything about the view template. You can also use ->pick to pick which template to use if it's going to be different than the controller and action it's ran in.
You can also return a response object from within a controller and Phalcon will not try to render the templates and use the response object instead.
For example you might want to do:
return $this->response->redirect('index/index');
This would redirect the user's browser to said page. You could also do a forward instead which would be used internally within Phalcon to access a different controller and/or action.
You can config the directory the views are stored with setViewsDir. You can also do this from within the controller itself, or even within the view as late as you want, if you have some exceptions due to a goofy directory structure.
You can do things like use $this->view->setTemplateBefore('common') or $this->view->setTemplateAfter('common'); so you can have intermediate templates.
At the heart of the view hierarchy is <?php echo $this->getContent(); ?> or {{ content() }} if you're using Volt. Even if you're using Volt, it gets parsed by Phalcon and generates the PHP version with $this->getContent(), storing it in your /cache/ directory, before it is executed.
The idea with "template before" is that it's optional if you need another layer of hierarchy between your main template and your controller template. Same idea with "template after" etc. I would advise against using template before and after as they are confusing and partials are better suited for the task.
It all depends on how you want to organize your application structure.
Note you can also swap between your main template to another main template if you need to swap anything major. You could also just toss in an "if" statement into your main template to decide what to do based on some condition, etc.
With all that said, you should be able to read the documentation and make better sense of how to utilize it:
https://docs.phalconphp.com/en/3.2/api/Phalcon_Mvc_View

Redirecting controller control to sub-controller

I'm using FuelPHP for my website. Currently, I've the following structure:
-folder1
-FILEHERE.php
-folder2
...
-fuel
-app
-classes
-controller
-learn.php
-folder1.php
-public
I've created a controller in fuel->classes->controller with the name learn.php. Now what I want is this:
If the person visits http://example.com/learn -> this controller fires up (learn.php).
I want to add a sub-controller and throw control to that whenever there is a next directory request. i.e.:
http://example.com/learn/folder1 should throw control to folder1.php in fuel->classes->controller.
How do I do this? I've checked the methods action_* but they don't look flexible.
Also, once the user visits something like: http://example.com/learn/folder1/FILEHERE
It should load the content file from folder1->FILEHERE.php (see the directory layout above)
Thank you for your help!
You can easily do this using FuelPHP's routing functionality. Which is documented here.
Your basic route config for the folder1 controller might look something like this:
'learn/folder1' => 'folder1/index',
The documentation outlines more complex examples as well if needed.

CodeIgniter - Stuck with routes

I am trying out CodeIgniter 2.1.4. I already have a controller for showing static pages which I built using the tutorial in CodeIgnitor documentation. I later set-up my routes like this:
// <http://localhost/> refers to <http://localhost/pages/view/>
$route['default_controller'] = "pages/view";
// <http://localhost/somepage/> refers to <http://localhost/pages/view/somepage/>
$route['(:any)'] = "pages/view/$1";
// .htaccess is already setup to rewrite the url without index.php
Now, I don't have much experience with PHP, and the concepts of URL Rewriting and MVC Architecture are fairly new to me.
Let's say there's are pages called •Home, •About, •Admin and •Contact.
For the pages •Home, •About and •Contact, the Pages controller works right as it should.
But for •Admin page, I want to have a separate controller which determines whether the user has logged in or not, and whether he has admin rights etc. And if he hasn't logged in yet, I should load the Login view instead of the Admin view.
The Pages controller has a fairly simple logic. It checks whether the string in argument, appended with .php and prepended with the views directory, exists as a file or not. If it doesn't show_404(), if it does, load view header-template, then load the page, then load view footer-templat. I'm pretty sure most of you who have worked with CodeIgniter must've seen a similar logic for static pages.
I could do redirect('login') inside my Admin view, but that doesn't seem to work. If I create a separate controller for Admin, how would I access it, while according to routes, every URL gets directed to pages/view controller (line#4 in the above code).
As I've already said, I'm fairly new to this. It might be some retarded mistake that I'm making. Or my whole MVC structure might be inappropriately built. How do I get past this and start worrying about the authentication stuff? Can anyone advise?
$route['default_controller'] = "pages/view";
$route['admin/(:any)'] = "admin/$1"; //(admin controller) with "any" method
$route['(:any)'] = "pages/view/$1";
localhost/poject/admin/edit as example
The problem you are experiencing is simple, you overwrite all controllers by that (:any) it isn't wrong but you need to manualy assign each controller that you want route as normal controller as I posted above.
please note that routes are order dependant and if one (first) is used second one is ignored. "Routes will run in the order they are defined. Higher routes will always take precedence over lower ones."
For authentification please see this post.
I would rather use _remap() and extend CI_Controller to take over my routes instead of having this route $route['(:any)'] = "pages/view/$1"; in routes.php.
remapping

how to include file in zend framework view?

I am newbie to the zend framework.
I want to know how to includes files in zend framework views.
I am using index.phtml to show the data in zend framework.
index.phtml contains some php pages like:
require_once ('/_incl/functions.php');
include('../functions.php');
Now I want to know where I put these files and call to index.phtml page.
What I can do to include these files, means where is the right place to keep all these files, and call from index.phtml page.
I totally understand how it feels to be a newbie.
No, you do not INCLUDE anything. If there is something you want to happen but have no option for it in zend, you make your own library and structure the class names accordingly. For example:
Zend_Form_Element is a class which is Zend / Form / Element.php
What you do is, make a class file and then, compile it.
To get started I would recommend going through this tutorial on tutsplus.
http://net.tutsplus.com/tutorials/php/zend-framework-from-scratch/
So, make a controller , make views, pass values from controller and then echo it in views.
Try to follow the rule-book rather writing codes in traditional method. :)
Hope you learn faster :)
I have simple way to include file in zend view page.
Just create one folder named 'include' inside public folder and store the file which you want to include.
After that write the following line in above the page where you want to include the file.
**include_once "./<include folder name>/<include file name>.php";**
Thanks......p2c

New pages in CodeIgniter on a big website

I have a website with many scripts written in "pure" PHP, i.e. no specific framework has been used to write the files. Furthermore, all the URLs are custom using .htaccess and specific PHP scripts.
For a smooth transition, I would like to start using CodeIgniter for new pages without disrupting access to the old pages, but all the documentation I've seen on CodeIgniter gives the impression that the whole website (perhaps with a few exceptions) needs to be based on the framework.
Would it be possible to use the framework for single pages here and there while leaving old URLs and code intact?
Short answer, yes.
You could access the CI framework from a subfolder, for instance, leaving the existing site untouched.
i.e
www.site.com/my_new_app/controller/method/
where my_new_app is the renamed application folder.
I'm going to go on the assumption that you already have a basic template system in place, and are able to render full pages with your existing site. Since Codeigniter is really just a framework, there's nothing to stop you from using vanilla php, like include, or additional libraries and classes. So, one thing you can do is dump your site into a sub directory in your views folder, then create a "master" controller which does nothing but load full html pages.
class Master extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
// We're expecting something like "registration/how-to-apply" here
// Whatever your URL is. The .php extension is optional
$args = func_get_args();
$path = 'path_to_my_old_site/'.explode('/', $args);
$this->load->view($path);
}
}
// Then use this in config/routes.php
$route['(:any)'] = 'master/index/$1';
This will route all pages through the master controller. So, yoursite.com/pages/faq will load the file application/views/old_site/pages/faq.php. You can apply different routes as you see fit.
This way, you can take your time migrating to use Codeigniter conventions, one page at a time.

Categories