kohana kostache partial logic - php

Started an project using kostache.
I have made some partials like banner,navigatons and footer in my class View_Layout with extends kostache_layout . Partials work fine on each page.
One problem. The navigation show always the same links. My goal is to show links that are appropriate to the user who is logged. How can I put logic in the partial of navigation? I know I can write functions in the View_Layout class but View_Layout must know the user role?
Hope somebody can help me.

In mustache, partials inherit from the surrounding template's variable stack. You'd need to do this logic in your view class. If different pages need different links, do that in your specific view class.

Option 1: evolve your views
The best option would be to expand the capabilities of your views. Actually in MVC-inspired patterns the views should be instances which handle UI logic and can choose from which (usually, more then one) templates to create the response. If that response even needs to be a HTML .. maybe a simple HTP header would be enough.
The default toolset in Kohana is geared towards very simple usecases, but it is possible to expand it.
My recommendation would be start using fully implemented views.
Option 2: use HMVC
Alternatively, you can utilize HMVC capabilities in Kohana. This would mean, that you have one or few "main controllers", which then create sub-requests. The responses from those requests is passed in/bound to the template, which said controller supervise.
In you particular case the menu would be governed by separate sub-controller.

Related

Zend Framework, setting up multiple templates for the same code base

Really not sure if the title of the question suits the question overall. But here goes.
What I have currently is an existing SaaS project. That we want to roll out a new template over time. Think of how google introduces new features. Or some other sites might with "Try our new Beta Version".. type of thing. Well we want to do the same, and then we will eventually phase out the old look and feel.
With that, this application is built on top of Zend Framework, so looking through docs I can figure out how to override the template on a given controller. But what I want to basically do, is likely going to make use of the sessions. If it exists, use this template. If not, use the old one.
Is it possible to override the default template in such a fashion? Right now for example, the default loaded file, is "tops.phtml" if the session exists I'd like to load "tops_v2.phtml" for example. So it can use that as the template instead of "tops.phtml" when the session is found.
Zend Framework 1.x solution:
You can disable ViewRenderer plugin in the action, and choose template manually:
public function indexAction(){
$this->_helper->viewRenderer->setNoRender(true);
echo $this->view->render("path/to/template/template.phtml");
}
I think that layouts are the thing you probably want to use, as was briefly touched on by Richie. Based on the question, I'm guessing you aren't already using them. Ultimately you can design a layout that defines the overall website look and then each of your action templates will only then render a fragment of the page (which will be dynamically placed in the content portion of the layout).
Using whatever logic you choose, you can then assign one of any number of layouts to be used on a given page load and of course you could store this as a user preference or something.

How should I divide my code using CodeIgniter?

I have searched the web and found only styling code posts. I want to write site using Code Igniter and I wonder how should I maintain my code.
For example:
Should I use one class for static pages and methods for each page or separate file for every static page. Should I use the same file to load dynamic pages or different one?
Can I use some common code and include it automatically to every class?
How can I have lets say header_view footer_view etc and then just load->view('whatever') and footer, header and other files would load automatically. Maybe there is better way to do that?
In generall what are the best practices when coding using CodeIgniter.
You can use one single class for static pages (and use one method for each page).
You can use the same one to load dynamic pages, but it is better IMO to load them with a separate class. It will be easier to maintain later.
Using common code: You can always override the CI_Controller with your own, and instantiating controllers from yours. Here is an example about how to do it.
You can load multiple views in a single controller function. A view doesn't have to be a full html document. You can also load the same view multiple times (for example in a loop).
Best practices: CodeIgniter is an MVC framework. IMO, MVC is a best practice. Always use the framework's documented features if they are suitable for what you want to achieve (CodeIgniter's documentation is very good. That link is momentarily offline, so please try this one).
Codeigniter is a MVC based framework, MVC is basically used for organizing your code, so at last its up to you how you are going to use it so ease you on the long term.
Basically when I design large projects in codeigniter I tried to to make unit of functionality at one place lets take example of any simple users, messages based project.
I tried to make functionality by grouping main topics, in this example user will be a controller, in that controller there will be methods like login, register, edit, listing, forgot_password now I'll create single model with all the methods which will give data for these above methods. by using this methods our urls will be also meaningfull like /user/login, /user/register etc
like that if its messages I will create controller message and add all related methods in it so that my related functionality will be in a single group.
as far as the question of static pages you can also group them in a single controller if they can be a part of group.
you can also use codeigniter's caching technique for static pages so that your pages will load faster

What are some PHP object-oriented framework initialization techniques?

I have an object oriented framework that uses a page design, where each page extends a view of the framework. So, for instance, my index page for a site is actually a class that implements the abstract class View provided by the framework. I hook the framework by including a startup script at the top of the page and after some processing the framework creates an instance of the page and processes its view data. To add flexibility to the system, I don't require the class name to be the name of the file itself. This allows me to create something like a support class and have it behave as the index for the /support/ subdomain.
I was initially passing the page's class name into the framework via the framework's constructor, but this added a few more steps to the top or bottom of the page. I currently obtain the class name via a pages table in the database identified by a filtered requested URI. I use this table to build navigation and adding an extra table column was practically free. This works OK as long as I have a database connection, but I'm trying to implement static page support for status messages and error reporting, and I need another method for creating an instance of the page's class. If I use the standard convention of naming the class the file's name, then I know I have a dependable way of extrapolating the class name. I don't really want to name all my classes index just for presentation reasons. What is some advice or some standards for how object oriented frameworks are initialized?
View.inc
<?php
abstract class View
{
abstract function getView();
}
?>
Startup.inc
<?php
require_once("View.inc");
require_once("CoreController.inc");
$Framework = new CoreController();
$Framework->Initialize();
exit;
?>
index.php
<?php
require_once("Startup.inc");
class Index extends View
{
public function getView()
{
echo "<pre>View Data</pre>";
}
}
?>
Within my framework I have a TemplateController that processes the page. The page class is known because it is mapped via another class. Without a database however, I would like to discover the class within, say, index.php without changing the way it's currently set up. Here is the actual code within the TemplateController.
//Get the View Class from Page
$view = $page->getPageClass();
//We need to catch View creation failure
$this->Page = new $view($this->Framework);
//Initialize the Page View
$this->Page->Initialize();
//Cache the Page View
$this->cacheView($this->Page, $page->getPageName(), $this->SiteID.TCS_PAGE_SORTID);
In the snippet above $view is the actual name of the class that was mapped from another controller. I'm passing a reference to the framework to the view's constructor and the rest is really irrelevant. I'm trying to come up with a similar mapping technique to identify the page class in the event the database is down. I like the one include line for the framework startup and would like to keep it that simple.
At the top of the TemplateController I have to also reinclude the actual page, since my startup script is at the top, the actual class is not included even though it is the requested page.
include($_SERVER['SCRIPT_FILENAME']);
Please review Stack Overflow question Identifying class names from $_SERVER['SCRIPT_FILENAME'] for more information on what I'm attempting to do.
Here is my checklist of page routing:
Adding new page must be quick
You must not be able to add page unintentionally
Application with million pages should not be slower or more bloated than application with 2 pages
Provide simple way and let people enhance it if they want
Allow easy re-factoring, such as moving several pages into different location
Make framework detect everything. Don't force user to specify base URL, etc.
Create simple to understand page names (hello/world).
Clean illegal characters from the URL
Make it possible to add static pages easy
Provide a way to generate URLs from page names.
Allow user to use pretty URLs by changing what appears before and after the page in the URL
And most importantly
- Stop copying, think about the best approach.
All of those suggestions I have used in the PHP UI framework - Agile Toolkit where I am a contributor.
Relevant sources: Agile Toolkit - a PHP Framework with jQuery, Agile Toolkit - PageManager.php, Agile Toolkit - URL.php and Agile Toolkit - PathFinder.php.
We wanted to make it really simple for developers. And secure too. And flexible. Therefore the "page" class is selected based on the URL. How? Quite easy:
/hello.html -> page_hello
/hello/world.html -> page_hello_world
Class then is mapped into filename. page/hello/world.php
Then there are cases when we want to use dynamic URLs too, such as: /article/234
Many frameworks implement a complex techniques here (arrays, regular expressions, front-controllers). We don't. There is mod_rewrite for this. Just rewrite this into page=article&id=234 and it works. And scales.
Apart from pages, there are other classes, but those classes can't be accessed directly. Therefore pages live under the /page/ folder, do distinguish them and maintain security.
Then comes the designer saying - "I won't write PHP". So we introduce static pages. If class page_hello_world is not defined, we'll look into template/skin/page/hello/world.html. That's a easy shortcut for designers and non-developers to add a new page.
What if a page is not found? Api->pageNotFound() is called. Feel free to redefine and load pages from SQL or display 404 page with a picture of a pink elephant.
And then there are some pages which come from add-ons. We don't want to enable them by default, but instead let users add them to their app somewhere. How?
class page_hello_world extends Page_MegaPage
Next question, is how we handle sub-pages of that page, since sometimes all the functionality can't fit on single page. Well, let's add support for page_edit() method (or any page_XX) as an alias for a sub-page inside those classes. Now add-on developer can include a multifunctional page which can be extended, customized and placed anywhere in the application.
Finally there are hackers, who want to do something really fast. For them we apply same technique to the API. You can define function page_hello_world in the API, and you don't need class.
Some might say that there are too many ways to do a simple thing. Oh well.
I hope that this was helpful.
Use __autoload(). Most major PHP frameworks use autoloading to streamline class loading.
You need some way to map a URL to an object, which is usually handled by a routing component in most frameworks. Might want to take a look at libraries such as https://github.com/chriso/klein.php, or the routing components of the major Frameworks out there (Zend, Symfony, etc.).
Why not to use information from URL to detect correct class? Since you won't use database for static pages, you have to somehow store mapping between URL and class in file. I.e. you will have a file mapping.php:
return array(
'about' => 'AboutView',
'copyright' => 'CopyrightView',
);
Here, about and copyright are URL components and values represent appropriate child classes of View. You can have URL's like http://example.com/index.php?page=about and use rewriting capabilities of webserver to make them look good.
You will change implementation of Page::getPageClass() in order to return correct view class. Depending on URL it will use static mappings from the file above or use database.
What's the problem with this approach?

Generate menu in Zend Framework

I am new to ZF and I have problem with even simple tasks.
I would like to have dynamically generated menu on every page. To do that I should fill $this->view with data. OK, but to do that, I would have to fill view separately in every controller I made. This would lead to code duplication.
The most natural solution, that I see, is to create base controller class for all my controllers, but I read, that this is not a good practice in ZF. So how should I do that? Even if it is only one line of duplicated code (eg. $this->view->menu = $reusableObject->generateMenuData()), I don't like it.
What is the best practice for such a solution? How could you solve this problem?
I am using ZF 1.11.
EDIT: I would like to mention, that I would be happy to know how to do that using some kind of phtml file rather than concatinating html tags.
EDIT2: The point is, I am not really interested in only navigation links. Instead of menu with links that could be eg. list of latest post, but on every page, so in every controller. I am particularly interested in "how to this kind of stuff in ZF".
Zend Framework has a Navigation component:
Zend_Navigation is a component for managing trees of pointers to web pages. Simply put: It can be used for creating menus, breadcrumbs, links, and sitemaps, or serve as a model for other navigation related purposes.
It also has some ViewHelpers to render various navigational elements out of it:
Breadcrumbs, used for rendering the path to the currently active page.
Links, used for rendering navigational head links (e.g. )
Menu, used for rendering menus.
Sitemap, used for rendering sitemaps conforming to the ยป Sitemaps XML format.
Navigation, used for proxying calls to other navigational helpers.
To prevent code duplication, use a Controller plugin that configures the Zend_Navigation instance and sets it to View or use Zend_Application_Resource_Navigation to configure it from your application.ini, which will then automatically assign it to the View Helpers.
Re your EDITs
You can use Zend_Navigation for arbitrary menues, not just the main navigation. Just configure it as you see fit and then render it with the appropriate helper. And if none of the Navigation helpers are what you are looking for, just write a helper or a partial that does the required output.
Whether you use a Controller Plugin to configure and inject it into the View or use a Helper that queries the Model for your Blog Post in the View Layout is up to you. Both is equally fine and possible.
Use Zend_Navigation. You can even configure it from your configuration file using the application resource plugin.

Where do you put non-controller classes in codeigniter?

I've got a class Widgets. Widgets are made up of Doohickies. I'm never going to need to access Doohickies directly via url -- they're essentially a private class, only used by Widgets. Where do you put your code to define the Doohicky class? In /app/controllers/doohicky.php? in app/controllers/widget.php? somewhere else? Obviously, the former seems cleaner, but it's not obvious to me how to make the Doohicky class available to Widget.
It sounds like your Widgets and Doohickies are probably Models in MVC architecture.
In which case, your paths would be:
app/models/widget.php
app/models/doohickies.php
I see the question has been answered already, but there are a few things to bear to expand on it.
You could put widgets and doohickies in the libraries folder, if they are there to do a job rather than provide a data service.
Also, take a look at HMVC, which favours the idea that you can have mini-apps that look after various parts of your website (e.g. messages panels, search box/results, doohickies...). This enables you to have smaller view partials dedicated to their widget controllers; and then the main controller calls in widgets but doesn't need knowledge of how they came about.
http://codeigniter.com/wiki/Modular_Extensions_-_HMVC/

Categories