I'm looking for advice, tutorials and links at how to set up a mid-sized web application with Kohana 3. I have implemented MVC patterns in the past but never worked against a "formalized" MVC framework so I'm still getting my head around the terminology - toying around with basic examples, building views and templates, and so on.
I'm progressing fairly well but I want to set up a real-world web project (one of my own that I've been planning for quite some time now) as a learning object.
I learn best by example, but example-based documentation is a bit sparse for Kohana 3 right now - they say so themselves on the site. While I'm not worried about learning the framework as I go along, I want to make sure the code base is healthily structured from the start - i.e. controllers are split nicely, named well and according to standards, and most importantly the business logic is separated into appropriately sized models.
My application could, in its core, be described as a business directory with a range of search and listing functions, and a login area for each entry owner. The actual administrative database backend is already taken care of.
Supposing I have all the API worked out and in place already - list all businesses, edit business, list businesses by street name, create offer logged in as business, and so on, and I'm just looking for how to fit the functionality into a MVC pattern and into a Kohana application structure that can be easily extended.
Do you know real-life examples of "database-heavy" applications like directories, online communities... with a log-in area built on Kohana 3, preferably Open Source so I could take a peek how they do it?
Are there conventions or best practices on how to structure an extendable login area for end users in a Kohana project that is not only able to handle a business directory page, but further products on separate pages as well?
Do you know any good resources on building complex applications with Kohana?
Have you built something similar and could give me recommendations on a project structure?
Bounty
I'm awarding the bounty to #antpaw because he provided me with a Kohana application with some business logic that is giving me a lot of examples. Cheers #Pixel Developer for your excellent input as well - as so often, I'd wish one could split a bounty!
Lots of questions to answer here, I'll try my best.
Do you know real-life examples of "database-heavy" applications like directories, online communities... with a log-in area built on Kohana 3 where I could take a peek how they do it?
There's a few example applications out there. Woody Gilk (Kohana founder) has published the code to his personal website on github. For the login area he assigns a cookie value. Kohana 3 / 2.4 sign the cookies which makes it safe and removes the requirement for sessions. This might not be up to everyone's tastes so you can always use built in authentication library that uses both sessions and cookies.
Here are some other projects you might be interested in:
Shindig - Light weight blog module for kohana 3
Kohanut - An extensible CMS written in Kohana 3
Are there conventions or best practices on how to structure an extendable login area for end users in a Kohana project that is not only able to handle a business directory page, but further products on separate pages as well?
If I understand you correctly you want to generate a login box for each of those pages? This is easy with Kohana 3 as we can take advantage of the H in HMVC. Sam de Fressyinet wrote an article detailing what this all about on the iBuilding Tech Blog. Scaling Web Applications with HMVC.
What you can then do is perform an internal request to the login controller or action and dump the response into your view page.
$login = Request::factory('login')->execute()->response;
$login now contains the login form, which you can put anywhere you like. You may want to return a different response if the request is internal which is why this piece of code can be useful:
if (Request::instance() !== $this->request)
{
print 'Internal called made with Request::factory';
}
Do you know any good resources on building complex applications with Kohana?
There's not going to be documentation showing you how to build complicated applications. The view of the Kohana community is that you're a PHP developer and should be able to solve these problems for yourself. If you can't, well you shouldn't be using Kohana then.
Have you built something similar and could give me recommendations on a project structure?
Once you understand how Kohana 3 finds files things are easy to understand.
|- classes
|-- controller
|-- model
|- views
For example:
Controller_Mathew extends Controller
Will look for a file called mathew.php in:
classes/controller
Underscores can be used to specify deeper directories. Example:
Controller_Mathew_Davies extends Controller
will look for a file called davies.php in:
classes/controller/mathew/
As you can see, the underscores in the controller name act as directory separators. This rings true for models and vanilla classes.
i would use the auth module that comes with kohana for the login. This will give you the roles table where you can setup the possible permission options and relating them to the users later. After that you can check inside the __constructor() or action_function() of each controller whether the user has the required role e.g. with the ->has() function. You also should use the ORM module, its just awesome, since you have many relations between the tables. Also the __get() method inside an ORM object can be extremely handy.
Its also pretty easy to extend a controller function by setting the new parameter to NULL and checking for that in a if statement. e.g. you need only one function for editing a old entry or adding a new one.
public funciton action_manage($id = NULL)
{
$entry = ORM::factory('entry', $id); // if id is null a new entry will be returned
}
It's also important that you structure the views into sub folders to avoid a messy view directory.
Related
So basically, I have this project I'm planning. A kind of "social network".
I was just wondering, as for now, I have a single controller (ProfilesController) wich takes care of status updating, profile editing, gallery uploading / viewing, settings etc.
Is this a good structure? Or should I separate it into different controllers like (ProfilesController, GalleryController, SettingsController, GuestbookController)?
And my models, I currently have Guestbook, PhotoAlbum, Profile and User models. Is this good? Or should some of theese maybe be merged into User or Profile?
Thanks in advance.
I think to keep things as RESTful as possible you should have separate controllers for the separate models. Your models should definitely each be their own files/classes.
1. Following the principle "single responsibility" okay that you create a controller for each process.
2. Laravel each table (that you used in the project) of the database must have a Model.
3. If you want to do good things would recommend to follow the principle "first API": Designing the structure of your API and then begin to program it. Having done this, recently begin to develop interfaces and your processes using your API.
I would stay with REST and really create For every table, a model and a controller. So you can develop your application in a very clean way.
If your "social network" or whatever application you want to develop will get bigger and more complex, this is the best way to keep it clean and clearly represented.
Once I started a small Project and was not really caring about following this principle, but you will get to the point you regret it.
So start your Project with a clean structure and create for every Model a Controller.
I recommend to also use the Route::Ressource for defining the basic routes. So you follow all the conventions.
Route::resource('Model', 'ModelController');
For more informations, check the docs.
I'm new to MVC and ZF2.
I carried out their tutorial successfully to build a basic app. (http://framework.zend.com/manual/2.1/en/user-guide/overview.html). In that tutorial they create a module called 'Album' to add/edit/delete music albums.
What I want to do is create an application that will have various functions, such as user account administration, system config, etc. I'm aware via reading other posts that you don't need to create a new module for each function, rather grouping them under one using entities.
With that in mind I set out creating my first module 'User' using this structure but I'm not sure if I'm doing it right. Structure I have at the moment is:
/module
/Application
/config
/language
/view
/src
/Application
/Controller
/UserController.php
/Entity
/User.php
/UserTable.php
/view
/user
/user
/index
If you want a look at the code check out the repo at https://bitbucket.org/newvisionjames/zf2-test/overview
Specific questions I have are:
1) I have two 'view' directories at the moment, pretty sure that's wrong..which one is correct, if either?
2) In the ZF2 tutorial they create two php files under /model called Album.php and AlbumTable.php. I have reflected this is my /Entity folder. Is this direct transfer correct? Does having an /Entity directory render the /model not necessary?
Overall what I'm trying to do is get set up with this framework so that it's working and I'll be able to learn from there but right now I'm stuck! Any helpful answers or pointers to useful resources will be much appreciated.
Thanks.
ZF2 follows PSR-0 standard which also improves the ability for other framework modules to interact with ZF2. To learn more about PSR-0 standard, take a look here: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
With your example above mentioning user, you most likely would keep user in it's own module due to the nature of "user". Does the user just contain a class to represent the user or does it include hooks for authorization and authentication etc? Also how is the routes handled? Although user may seem simple at first glance it's usually something that is placed in it's own module.
And that is so you can re-use / share your module with others. Generally whenever I build an app it would be moved into multiple modules depending on where the functionality fits. Then between modules if I need access to another module I will make use of the service locator to access those methods.
For instance under the application module I may want to reference the user's first name, i can call the user module service to then show me the user's details. This simplifies your code a lot.
To answer your questions directly though:
I have two 'view' directories at the moment, pretty sure that's wrong..which one is correct, if either?
Answer:
Based on your posted directory structure only the top level "view" directory looks correct in a "ZFSekeleton" representation.
In the ZF2 tutorial they create two php files under /model called Album.php and AlbumTable.php. I have reflected this is my /Entity folder. Is this direct transfer correct? Does having an /Entity directory render the /model not necessary?
Answer:
Technically you can put your business logic anywhere as long as it follows namespace / psr-0 standards. Beyond that there is no real requirements, although what is important to you use a coder is that you improve readability of your code or you won't get anywhere fast.
I normally like to seperate my src folders like so:
Controllers
Models
Adapters
Services
Entities
Where controllers is obviously the controllers for zf2. Models contains some business logic for controllers or classes. Adapters are authentication adapters, database adapters etc. Services are the service locator classes for other modules and the current module to work from. Entities are my data representations.
To each their own but that just makes sense to me. Hope that helps.
Well-written and nicely formatted question. Don't see that too often.
The higher-level one is right. The one that's at the same level as src. Everything under src will be class files. So they follow the PSR-0 standard, each file contains excatly one class, etc. So you don't want any views there.
Seems pretty good to be, but sice I use Doctrine instead of ZF2's ORM, I can't tell for sure. What I can tell you is that you don't need a model directory and that will probably put all of your entities inside Module\Entity. So that's absolutely right.
Overall I'd tell you this: Stick with the config, src, view folders. That's what ZF2 likes and this is what every other ZF2 developer will expect from a ZF2 module. Don't get too hung up on conventions inside your src folder though. You can pretty much put your stuff whereever you want in there. If you've got a decent IDE (like PhpStorm), it only takes a couple of seconds to move or rename classes later. Just go through some ZF2 modules on GitHub and try to match what groupings or hierarchies you see most often.
And here are some words about the separation of modules: I'd say it's a good practice to try and break your project up into modules as much as possible, as long as you think they could live separately. For example: You have an online shop with a bunch of products and a search function. Now ask yourself the following question: "Do the products need the search function?" No. The products can live without it. So you put the search functionality in its own ProductSearch module. Can blog posts live without their comments? Yes. Create a Blog and a BlogComment module.
The whole project structure is something I was thinking a lot about when I started out with ZF2. So if you have any more questions, just comment and I'll try to update my answer.
You should definitely read this post: http://akrabat.com/zend-framework-2/thoughts-on-module-directory-structure/
I'm building a simple Virtual Learning Environment(VLE) system for a test project with CakePHP. The project contains the following:
Courses
Lessons
Questions
Answers
I've made the Controller, Models and Views for the courses and Lessons and I'm able to add lessons to a course and delete them. I've generally been following cakePHPs blog tutorial and changing as I go along.
This however leaves me with a very rigid structure of content and pages and URL's (I understand how to change the URL's to be more user and SEO friendly with Routes). My pages are all /{controler}/{method}
Part of the project is to create a management panel for the courses. On the page you can see lessons, and the students assigned to the course with links to add/edit these.
I can not however work out how to do this combination of several models into an admin style page. I can think of a few ways of dong this involving perhaps cakePHP pages, or routes and bringing one models data into another's controller to get it into the view. However I am trying to find out the correct way of doing this with cakePHP or failing that in MVC frameworks in general.
I apologise if this is laid out anywhere obvious but I've looked and have yet of find any answer that coveres my issue is a laid out fashion. Unfortunately I really need this spelling out for me as I'm just overwhelmed with a lot of MVC without anyone to ask and haivng only worked in CMS systems.
Just create a Controller called "DashboardsController" or something like that.
Within it's actions, you can load any model(s) you want, then use it just as you would in the respective Controller:
$this->loadModel('Course');
$courses = $this->Course->find('all');
$this->set(compact('courses'));
This is a very common problem/solution, and I believe I even asked this same question a few years ago on here myself (though I couldn't find it). You still retain the MVC structure, as it still acts as the Controller - it just accesses methods from varying models.
It's incredibly common to call more than just the model of the controller you're in, so in a case like this, you just load whichever models you want/need.
You can make a Dashboard.php model as well and just set
$useTable = false;
to tell it you don't need a "dashboards" table.
I have one of these "generic" controllers in almost every project I do, and am not really sure of any other/better way to handle it. This seems the cleanest, easiest, and most logical approach IMO.
I am currently trying to understand how the MVC framework does work in PHP. Therefore, I have created this basic sketch of how I think that MVC is implemented in PHP:
[I know that some steps are missing, e.g. how the Routerparses the route in order to know what View and Controller to load, but these steps are rather technical based and are not important in order to understand the general flow of MVC in PHP.]
I draw my understanding of MVC in PHP from this article series. However, I think that this structure will differ from most of the structures people think off, when they talk about MVC in PHP, because of this article (The article basically states that not only the Controller but also the View does communicate with the Model).
What I'd like to ask you now are several questions:
Is this generally a right way of implementing MVC in PHP?
How can I add a Login/Logout-System to this approach? So that user, who are not logged in, will always see the LoginView and users who are logged in can see different views? (I know how a login system does work, but I can't figure out where to place it in the MVC, so I don't have to insert the code multiple times, e.g. in each Controller.)
What if my application consist of multiple elements (say a user bar [with user name, link to settings, etc.], a navigation and a content container) that are always loaded? How can I assemble these elements to a final view? (The only idea that comes to my mind is to assemble the final view in each view separately, but that would mean that I have to insert the code for it multiple times in each view, which misses the point of MVC, doesn't it?)
What if I want to use AJAX in my application? My idea would be to send ajax requests through the framework as well, while only accessing controllers and views that are made for ajax? In other words the AjaxViews do only return e.g. json objects and the AjaxControllers do always expect authentication codes to prove that these ajax calls are legtitim?
I know that there have already been asked dozens of questions about MVC in PHP and I've been reading quiet a lot of articles until now, but I think that only reading does not enable me to understand MVC completely.
Furthermore, after reading the articles linked above, I'm not longer sure whether other articles about MVC, I find on the web, does explain MVC the same way as the articles above. Because if they don't, I'm trying to understand one framework while reading about two or multiple different approaches.
Thank you very much in advance for taking the time to answer my question!
-- --- --- Update --- --- --
According to the answer below I've changed my MVC sketch. Just in case someone finds this link and wants to know more.
Let me first answer your questions, then place my take on it.
There's no right way of writing MVC. There are so many flavors and variations, and that get even multiplied when talking about web MVC.
About Logging in and Logging out. I think the most robust system would be a Role Based Access Control combined with an Access Control List, see How can I implement an Access Control List in my Web MVC application?.
There are generally two approaches, either you have a 1:1 ratio between Controllers and Views, and then after the Controller is done, your bootstrap script calls the View with the same name (LoginController, LoginView), or your Controller returns the View name along with action and parameters, to be called by the bootstrapper. The view then picks a template, and that template can include other sub-templates (like the user bar, or the footer).
In that case, your view needs to have an ability to select a different template based on the Accept: HTTP header (and send something like Accept: application/json in your AJAX requests). Your view then returns a JSON template instead of an HTML template.
What is wrong with your sketch?
Your model isn't just the gateway to your database, it's where all the logic happens. All the computation. See this yet another excellent answer that explains How should a model be structured in MVC?.
The idea of MVC is to simply separate your application into three layers: Input (controller), Logic (model) and Output (view). This is to extend on the usual way PHP works (here's a request, give me a response, all in the same page).
For that reason, implementation details may vary, the concept is what matters. "Web MVC" is merely the result of good OOP practices and some naming convention someone made up a few decades ago.
It is for parallel development and code reuse ability. There is a separation of concern how your system works and how users work. This provides a solution of the problem. There is boundry now, MVC.
I've been learning CodeIngiter and up till now but can't seem to get a grasp on how CodeIgniter can be used to work as a team. Can someone explain the basic of team work using CodeIgniter?
From what I understand, it's like this so correct me if I'm wrong :
Let's say there is a project with 5 pages, Home, About Us, News, Gallery and Contact Us. Where CodeIgniter can help is let's say I have 2 programmers in my team, so each one of us do a module (for each Controller-View-Model) (for example Programmer A does News module, Programmer B does Gallery module) in different folders (folder news and gallery), etc.
So the end product will be a group of modules in seperate folders. home/ , content/, news/, gallery/, contact/ , etc.
Is that the right flow of teamwork using CI? I read that CI can be used to collaborate between designers (front end CSS) and programmers (database and controller) but I think with this flow, designers will have to wait for programmers to get the variable names to be parsed into the view and that will somehow halt the progress of the work.
I currently work in a team environment with Codeigniter and I'll tell you generally it flows like this.
Designer produces Designs coded out (html/css) with static content. (no variables)
While he is doing that Myself and others are working on the data model we are going to use and writing Model Methods we can forsee needing to interact with the data in a way our application will utilize.
Then the Designer hands off the static layouts, I "cut them up" into header/footer/etc... and replace the static content with the variables by writing the controllers to accomodate.
As a bonus I would highly recommend using some sort of version control with your team, depending on your needs I usually stick with SVN or GIT, GIT is a little more accommodating to distributed teams that are not in a centralized location. This will greatly improve efficiency and prevent ( or mitigate ) situations in which two people end up working on the same file and someones work gets overwritten, and other situations that occur when multiple people are working on the same files.
CodeIgniter is just one way of doing of Model-View-Controller. You probably don't need to divide things up into separate modules or folders; instead, you'll probably want to create files like this:
controllers/gallery.php
controllers/home.php
controllers/news.php
views/gallery_view.php
views/home_view.php
views/news_view.php
models/page.php
models/picture.php
It's perfectly legal for each controller to make use of multiple models and views; in fact, that's the point. A blog controller might use models for user, post, and comments. You can also do sub-views which are used from inside your other views (such as views/header_view.php).
If your project has well-defined specs, you might consider making the team division between one person doing the model and controller logic, and another writing the view output. Or, you could divide the work between different pieces of the site; however, you'll still want to write some shared code that gets used project-wide. That's the biggest principle of MVC: Don't Repeat Yourself.