I have a controller that extends Zend_Controller_Action. It contains some actions that I need to give people access to via a RESTful MVC web service.
I've seen some articles that have told me to extend using a different class (Zend_Rest_Controller) but this seems to mean I need to override certain abstract methods and really I no use for most of them (I have my own functions that are quite specific!).
I've seen some code that I've meant to copy into my bootstrap.php and makes use of the FrontController. However, everything I've seen is awfully documented.
Can anybody give me an example that will just work for a controller called, say 'catalog' that contains two actions 'getRoot' and 'checkLatest'? (It should be simple yet I can't get anything to work and have a deadline tomorrow!)
Or else, perhaps point me in the right direction... (I've no idea how to troubleshoot this and see, for example, what URL I should be using to test or where the route I have setup is directing this... I've been looking at this, btw: http://techchorus.net/create-restful-applications-using-zend-framework)
Thanks a lot! :)
In the article that you mention you have a class:
class ArticleController extends Zend_Rest_Controller
Just like that example you should create a CatalogController. The different methods that you require should be sent as parameters HTTP GET parameters. The getAction should perform the operations (depending on your request) and return a collection of of results in the response depending on different possibilities such as "getRoot" or "checkLatest" as you mention.
Related
I am attempting to create a controller that can detect if it is called from another controller in the application.
If it called directly via the URL, however, I need to know so I can perform some other actions.
i.e.
cheese/modulename calling potato/modulename is different to someone accessing site/cheese/modulename via URL - and I need to be able to pick up on this and act accordingly.
I am aware of:
$this->router->class
but it will not work as I may have the same named class in another module (HMVC pattern as an FYI) that may want to call this controller (cheese/modulename calling potato/modulename as an example would return 'modulename' - so I can't use that as a check to see if it was called by itself.)
I basically need a check for:
controller was called via another controller = true / false
can anyone tell me how (or if I am being thick!)
I am doing this in the __construct() just in case your solution will have a problem with that (can't see why but you never know!)
EDIT
Thank you to Mohammad Walid for his answer.
For clarity the structure is
CLIENTS
MODELS
CONTROLLERS
- Client
- Api
VIEWS
JOBS
MODELS
CONTROLLERS
- Jobs
- Api
VIEWS
I will be calling the API from Client - but may also call it from another API (possibly) That may be
In another Module
For Example the CLIENTS Api might get called from the JOBS Api Controller (I have no intention of doing this at present but it may be a possibility under different scenarios I haven't forseen and want to make it future-proof so I don't have a massive refactoring job in the future.)
You can try this:
function is_called_via_url($controller_object){
return $this->uri->segment(1) === get_class($controller_object);
}
and in your controller:
if(is_called_via_url($this)){
//do something
}
I'm not quite sure if passing $this as an argument in the constructor will work, but it worth try.
Reference and a hint from MonkeyZeus's comment.
From the comments there seems to be no way to do this without using debug_backtrace($options, $limit)
However the work-around I have ended up doing is to add a 'flag' within the authorisation module (which is called before all controllers)
The flag defaults to false.
If a controller from within my application calls the API page I turn this flag to true (is_application = true - I am currently just manually pasting this into the __construct of any controllers in my application that need to talk to my API)
I can then just do a simple
if(!is_application){
//this was called directly from the URL not from within the application
}
from within the API controller.
Hopefully this will be helpful for others who are attempting this sort of thing and once again thank you to the people who took the time to comment / answer.
I am making website, that will be used by 2 different user types. And both types have different controllers. But some things are common for both users, specifically I want to make a class that will contain methods that will be run when either user logs in (it will check some stuff like is email confirmed etc etc..)
Anyway, I tried to create new library, and that worked sort of.. But there are problems because $this is not available, and I need to use $CI, which needs to be redeclared on every method.. so it is a bit of a pain.
Any better way to do it?
Extend the Controller class. Have a look here:
Codeigniter MY_Controller
As I understand it, MVP is a derivative of MVC where the Model and the View are loosely or completely decoupled, and the Presenter replaces the Controller and acts as the bridge between the View and the Model. This pattern seems more appropriate than traditional MVC in web applications (whether or not that is true is not the subject of this question, so please refrain from going down that direction).
My problem is in implementing the various MVP pieces in PHP, using a passive view. Here is my current flow of things:
The PHP script sets up an autoloader and a router. To me, this means whatever view was in existence send an event of some kind to the server.
The router then determines which presenter should be used based on the request.
Here be dragons. The Presenter acts as the bridge between the View and the Model and should take a View and a Model as dependencies so it can easily be tested. That means I need to know what model and view I should be using before the presenter is created.
The presenter seems to be the class that knows what Model and what View it needs, so how can I move that logic out of the presenter? I understand that the generic pattern to use is a factory, I just can't seem to understand how to implement it in this case.
Perhaps I am doing this all wrong. Maybe I've been coding for too long of a stretch and am experiencing mind warp. Regardless of why I can't seem to understand how to solve this problem, I'll accept any guidance.
Not 100% sure I know what you're asking. You are right that you load the appropriate controller based on the request. That controller is typically associated with a model and a view.
Let's say you have a URL that looks like: http://www.example.com/test/view/1
It would be fairly standard to load the Test controller, call the method view pass it the argument 1. So let's assume you have:
TestController.php
TestModel.php
test.php (view)
When the TestController loads it includes the model, TestModel, where your "data stuff" goes (I think you understand that). So for this example, let's say view wants to load the last 5 posts from the user with id 1. So in TestController.php:
function view($arg)
{
$userID = $arg;
$posts = $this->model->loadPosts($userID);
$this->render('test', $posts); // outputs the HTML in test.php
}
And in test.php, you can loop through $posts and output it however you choose.
It seems like you already know how this stuff works though, which is why I am confused as to what you're asking. Does this clear up anything?
I find it useful to think of Web Apps in terms of states and state transitions. the application is in a particular state, it's "at" a View, some HTML was with the aid of the associated Presenter from data in the Model and rendered to the browser . The user takes an action and this is going to move our app to a new state. So we are moving from one View/Presenter pair to another. In my mind the Model is a longer lived, evolving thing, I don't see us getting a new Model for each transition.
So you have PresenterA, responsible for responding to events in ViewA.
PresenterA receives some event, performs some work that may result in Model changes, and then decides which View to go to, say ViewB. ViewB can create its Presenter. As per the Wikipedia example (not PHP I realize, but the principle is clear):
public class DomainView: IDomainView
{
private IDomainPresenter domainPresenter;
public DomainView() // Constructor
{
this.domainPresenter = new ConcreteDomainPresenter(this);
}
}
In effect the Presenter is the creator of the next View/Presenter pair. If you have more complex logic replace the explicit constructor
new ConcreteDomainPresenter(this);
with a factory, working with View and Model information.
I've been working on creating my own MVC app in PHP and I've seen a lot of differing opinions online about how exactly this should be set up. Sure, I understand there seems to be a general "It's MVC, it is what you make of it" approach, but I'm running into 2 seemingly conflicting viewpoints.
A little background on my app: I'm using smarty as my presenter and an object-oriented approach. Seems simple enough, but I'm trying to figure out the ubiquitous "what is a model" question.
If I take a look at some tutorials and frameworks, they seem to view the model as strictly a class that inherits DAL methods from an abstract class, with a little bit extra defined in the class itself as your data needs differ from object to object. For example, I might see something like $productModel->get(5) that returns an array of 5 products from the database. So what if I need to query multiple models? Do I store all of the data in the controller or an array and pass that to the view? Then if I'm dynamically calling my controller, how can I persist the data unique to the controller necessary to render the view? This seems bad, especially because I then have to pass in things like "controllerName", "controllerData", and my View::render() method gets hugely bloated with parameters, unless I pass in the controller itself. Maybe I'm missing something here.
Let's say I want to make a login that queries a users table. Login is a model or a controller, depending on certain implementations I've seen online. Some implementations (I'll call this method 1) make a LoginController with method login() that might do a comparison of $_POST and what's returned from the user model instance $user->get(1) to see if a user is validated. Or maybe login() might be a method in a default controller. On the flipside, an implementation (implementation method 2) that resembles more of a Joomla approach would make a Login model and declare all of the actions inside of that. Then any data that needs to get assigned to the view would get returned from those methods. So login->login() would actually check post, see if there's a match, etc. Also the User model would probably be instantiated inside that model method.
My feelings about 1: The controller is fat. Additionally the controller is storing data pulled from models or passing in ten thousand variables. It doesn't seem to jibe with the idea that the model should be passing data to the view that the controller should be blind to. Also, let's say I want to wrap everything that is in a specific model handled by a specific controller in an outer template. I'd have to copy this template-setting code all across my controller functions that interface with this model. It seems grossly inefficient.
My feelings about 2: It doesn't make for having actions that aren't model methods. If I want to go to my site root, I have to make an index model or something that seems like overkill in order to have a model that passes data to the view. Also, this doesn't seem to be a very popular approach. However, I do like it more because I can just do View::render(mymodel->func()) and ensure that the data is going to be passed back just the way I like it without having to crap up my controller with code merging a thousand query results together.
I've waded through far too many religious arguments about this and want to know what you guys think.
I've built my own framework in the past too so I know what you're going through. I've heard the saying "build fat models" and I agree with that -- as long as the main goal is to return data. I considered the controller to be "The Overlord" as it manipulated data and directed where it should go.
For a login controller i might create something it like...
Post URI: http://example.com/login/authenticate
LoginController extends ParentController {
public function authenticate() {
$credential_model = $this->getModel('credentials');
// Obviously you should sanitize the $_POST values.
$is_valid = $credential_model->isValid($_POST['user'], $_POST['email']);
$view = $is_valid ? 'login_fail.php' : 'login_success.php';
$data = array();
$data['a'] = $a;
// .. more vars
$this->view->render($view, $data);
}
}
In my opinion data should always flow from the model -> controller -> view as it makes the most sense (data, manipulation, output). The View should only have access to what it has been given by the controller.
As for this...
Then if I'm dynamically calling my controller, how can I persist the data unique to the controller necessary to render the view?
Well I would imagine you're building a 'base' or 'parent' controller that gets extended off of by your dynamically called controllers. Those child controllers can have properties that are needed for for the view to render -- honestly I'd need an example to go further.
Hopefully this helps a bit. If you ask more specific questions I might be able to give a better thought out opinion.
If you're writing your own app, I think the best solution is to do it yourself and find out.
Ultimately, whatever makes the most sense to you, and whatever makes it easier for you to conceptualize your app and quickly add to or change it, is going to be your best option.
If one way is "wrong", then you'll find out through experience, rather than someone else telling you. And you'll know the entire situation that much better, and know EXACTLY why one way is better.
What helped me when I was writing my own framework in PHP was, strangely enough, CherryPy. It made the concept of an object-oriented web app so simple and obvious, and I enjoyed using it so much, that I modeled the basic structure of my PHP framework to imitate CherryPy.
I don't mean to imply you should learn CherryPy. I mean that simplicity, clarity, and enjoying developing with your own web app go a LONG way.
If I were to give one piece of specific advice, I'd say try to avoid retyping code; write your code to be reusable in as many situations as possible. This will not only be good for your app, but for future apps you may write or work on.
You might check out Eric S. Raymond's Rules for Unix Programming. I think they're definitely applicable here.
I am learning the PHP MVC pattern for my backend implementation. Looking at this excellent example:
Implementing MVC in PHP: The Controller
http://onlamp.com/pub/a/php/2005/11/03/mvc_controller.html
I feel comfortable with the execution flow in a GET.
But there is no mentioning of what happens in a POST. What would the typical controller code for the POST do? I wonder if I am misunderstanding something obvious here, since I can't find similar situations in previous SO posts or Google.
For example: An app to manage persons,(name, last, age) wants to add a record to db when a POST hits the controller.
What happens next?
My guess is that the 'View' is not used at all, or maybe for confirmation?
Is there just a call from the controller to a model class that adds a record to db?
Or do I skip the controller altogether for a POST and go directly to an "add record" script?
Is there any available example?
Thanks in advance,
Ari
Well, POST is basically the same as GET, just some random chunks of info client sended to server. So you can treat it the same way.
I worked with CodeIgniter MVC framework in PHP. It uses GET URI to route to controller and it's methods. When the POST request comes, it treats its URI in the same way. The later actions are in the hand of the programmer, who accesses POST request data directly or through some wrapper, and he can also don't use it at all.
I need to say that you focus on the wrong parts. MVC is not the model of everything, and it doesn't say how to treat POST or GET requests. It's just a simple principle known many years before the name "MVC" became famous as the principle about splitting of logic, data and representation. And most of software(from old to new) actually do this splitting, because it is very hard not to do this in most cases. In some apps the borders are not so evident, some of them even haven't object model. The implementation of the app is always up to you, because MVC doesn't say you what to write but just gives some clues about highest level organization of you code.
P.S. Sorry for my bad English.
Typically, the controller would process the request (the controller processes ALL requests), then call into the model to actually manipulate data based on the request, and then either redirect to somewhere else (triggering a new GET request), or invoke a view to output a resulting page.
Well, if you are going to build your own MVC pattern solution, you could make one tricky thing. Since you're handling MVC you're supposed to have a really reliable routing manager. So after parsing your URL and defining what controller/method you are supposed to trigger, you could make something like:
<?php
...;
$method_name = (count($_POST) > 0) ? "post_".$route_result : $route_result;
...;
and later in your controller class you could do something like:
<?php
namespace Controllers;
class MyController extends \System\Controller {
function my_method($whatever = null){
...;
return $this->view($model_or_whatever); // supposed that you prepared view Class in routes
}
function post_my_method($whatever = null){
...;
return $this->view($model_or_whatever); // supposed that you prepared view Class in routes
}
}