PHP头条
热点:

CakePHP官方博客示范教程


CakePHP 官方博客示例教程

初识CakePHP,感觉不错;

按照官方的博客示例教程练习了一下,有点自信继续学下去了。下面是示例:

地址:http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html

?

?

Blog Tutorial - Adding a layer

Create a Post Model

The Model class is the bread and butter of CakePHP applications. By creating a CakePHP model that will interact with our database, we’ll have the foundation in place needed to do our view, add, edit, and delete operations later.

CakePHP’s model class files go in?/app/Model, and the file we’ll be creating will be saved to?/app/Model/Post.php. The completed file should look like this:


class Post extends AppModel {
}

Naming convention is very important in CakePHP. By naming our model Post, CakePHP can automatically infer that this model will be used in the PostsController, and will be tied to a database table called?posts.

Note

CakePHP will dynamically create a model object for you if it cannot find a corresponding file in /app/Model. This also means that if you accidentally name your file wrong (i.e. post.php or posts.php), CakePHP will not recognize any of your settings and will use the defaults instead.

For more on models, such as table prefixes, callbacks, and validation, check out the?Models?chapter of the Manual.

Create a Posts Controller

Next, we’ll create a controller for our posts. The controller is where all the business logic for post interaction will happen. In a nutshell, it’s the place where you play with the models and get post-related work done. We’ll place this new controller in a file called?PostsController.php?inside the?/app/Controller?directory. Here’s what the basic controller should look like:


class PostsController extends AppController {
    public $helpers = array('Html', 'Form');
}

Now, lets add an action to our controller. Actions often represent a single function or interface in an application. For example, when users request www.example.com/posts/index (which is also the same as www.example.com/posts/), they might expect to see a listing of posts. The code for that action would look something like this:


class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
}

Let me explain the action a bit. By defining function?index()?in our PostsController, users can now access the logic there by requesting www.example.com/posts/index. Similarly, if we were to define a function called?foobar(), users would be able to access that at www.example.com/posts/foobar.

Warning

You may be tempted to name your controllers and actions a certain way to obtain a certain URL. Resist that temptation. Follow CakePHP conventions (plural controller names, etc.) and create readable, understandable action names. You can map URLs to your code using “routes” covered later on.

The single instruction in the action uses?set()?to pass data from the controller to the view (which we’ll create next). The line sets the view variable called ‘posts’ equal to the return value of the?find('all')?method of the Post model. Our Post model is automatically available at?$this->Post?because we’ve followed Cake’s naming conventions.

To learn more about Cake’s controllers, check out the?Controllers?chapter.

Creating Post Views

Now that we have our data flowing to our model, and our application logic and flow defined by our controller, let’s create a view for the index action we created above.

Cake views are just presentation-flavored fragments that fit inside an application’s layout. For most applications they’re HTML mixed with PHP, but they may end up as XML, CSV, or even binary data.

Layouts are presentation code that is wrapped around a view, and can be defined and switched between, but for now, let’s just use the default.

Remember in the last section how we assigned the ‘posts’ variable to the view using the?set()?method? That would hand down data to the view that would look something like this:

// print_r($posts) output:

Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 1
                    [title] => The title
                    [body] => This is the post body.
                    [created] => 2008-02-13 18:34:55
                    [modified] =>
                )
        )
    [1] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [title] => A title once again
                    [body] => And the post body follows.
                    [created] => 2008-02-13 18:34:56
                    [modified] =>
                )
        )
    [2] => Array
        (
            [Post] => Array
                (
                    [id] => 3
                    [title] => Title strikes back
                    [body] => This is really exciting! Not.
                    [created] => 2008-02-13 18:34:57
                    [modified] =>
                )
        )
)

Cake’s view files are stored in?/app/View?inside a folder named after the controller they correspond to (we’ll have to create a folder named ‘Posts’ in this case). To format this post data in a nice table, our view code might look something like this:



Blog posts
                                         foreach ($posts as $post): ?>
                                     endforeach; ?>
     unset($post); ?>
Id Title Created
echo $post['Post']['id']; ?> echo $this->Html->link($post['Post']['title'], array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?> echo $post['Post']['created']; ?>

Hopefully this should look somewhat simple.

You might have noticed the use of an object called?$this->Html. This is an instance of the CakePHP?HtmlHelperclass. CakePHP comes with a set of view helpers that make things like linking, form output, JavaScript and Ajax a snap. You can learn more about how to use them in?Helpers, but what’s important to note here is that the?link()method will generate an HTML link with the given title (the first parameter) and URL (the second parameter).

When specifying URLs in Cake, it is recommended that you use the array format. This is explained in more detail in the section on Routes. Using the array format for URLs allows you to take advantage of CakePHP’s reverse routing capabilities. You can also specify URLs relative to the base of the application in the form of /controller/action/param1/param2.

At this point, you should be able to point your browser to?http://www.example.com/posts/index. You should see your view, correctly formatted with the title and table listing of the posts.

If you happened to have clicked on one of the links we created in this view (that link a post’s title to a URL /posts/view/some_id), you were probably informed by CakePHP that the action hasn’t yet been defined. If you were not so informed, either something has gone wrong, or you actually did define it already, in which case you are very sneaky. Otherwise, we’ll create it in the PostsController now:


class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index() {
         $this->set('posts', $this->Post->find('all'));
    }

    public function view($id = null) {
        $this->Post->id = $id;
        $this->set('post', $this->Post->read());
    }
}

The?set()?call should look familiar. Notice we’re using?read()?rather than?find('all')?because we only really want a single post’s information.

Notice that our view action takes a parameter: the ID of the post we’d like to see. This parameter is handed to the action through the requested URL. If a user requests /posts/view/3, then the value ‘3’ is passed as?$id.

Now let’s create the view for our new ‘view’ action and place it in?/app/View/Posts/view.ctp:



 echo h($post['Post']['title']); ?>

Created: echo $post['Post']['created']; ?>

echo h($post['Post']['body']); ?>

Verify that this is working by trying the links at?/posts/index?or manually requesting a post by accessing/posts/view/1.

Adding Posts

Reading from the database and showing us the posts is a great start, but let’s allow for the adding of new posts.

First, start by creating an?add()?action in the PostsController:


class PostsController extends AppController {
    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');

    public function index() {
        $this->set('posts', $this->Post->find('all'));
    }

    public function view($id) {
        $this->Post->id = $id;
        $this->set('post', $this->Post->read());

    }

    public function add() {
        if ($this->request->is('post')) {
            $this->Post->create();
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash('Your post has been saved.');
                $this->redirect(array('action' 
www.phpzy.comtrue/phprm/31739.htmlTechArticleCakePHP官方博客示范教程 CakePHP 官方博客示例教程 初识CakePHP,感觉不错; 按照官方的博客示例教程练习了一下,有点自信继续学下去了。下面是示例: 地址:http://book.cakephp.org/2.0/en/...

相关文章

PHP之友评论

今天推荐