开发者

Design Guideline - New To CakePHP and MVC

I am new to CakePHP and MVC in general. I am trying to create a web application for my friends and family.

I would like to have a login form at the top of开发者_JAVA百科 the page, and a listing of events in the body. I would like the events to be displayed even if the user is not logged in. When the user logins using the form at the top I would like the events listing to update with additional information that would not be displayed to a user who is not logged in.

I want similar functionality on other pages as well.

What I have done so far: 1) Create a layout that contains my header and footer. 2) Include in the layout a custom "Element" that is the login form.

Ideally what would happen is when you typed in your login information, the login "Element" would send a ajax request to validate the login. It would then update and say something like "Welcome User". I would also like it to then send another ajax request to a update method of the current controller, whatever that may be. The current controller would than change what was displayed on the page, if anything was login dependent.

Is this a good design? Is it feasible which CakePHP. So far in searching it seems that "Elements" are meant to be self contained and having it call a function of the "current controller" seems odd.

Any help would be appreciated.

Thank you.


Yes, your design is feasible. Your controller actions always render a 'view'. No, what you put into that view is up to you. It can be as little as an element.

You will need to have the login form/button make a call to the login action and have it render the return as json. You'll want to update the login function to handle responding to an ajax request. This can be annoying to set up so I'm going to provide some code.

Be sure to include RequestHandler component and Js helper in your app controller.

app/controllers/users_controller.php:

function login() {
    if($this->RequestHandler->isAjax()) {
        ...
        $this->set('status', /*whatever data you want to send*/);
        // Explicit call to render an ajax response, using a layout and view made specifically for ajax
        $this->layout = 'json';
        $this->render('ajax_login');    
    }
    // render views/users/login.ctp like normal
}

Your app/views/layouts/json.ctp file:

<?php
    header("Pragma: no-cache");
    header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
    header('Content-Type: text/x-json');
    header("X-JSON: ".$content_for_layout);

    echo $content_for_layout;
?>

Your app/views/users/ajax_login.ctp file:

<?php echo $js->object($status); ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜