Controller not found cakephp 3

3.4k views Asked by At

I am new to cakephp. I just created a project test in cake php using below line

php composer.phar create-project --prefer-dist cakephp/app test

After that I import this project in netbeans

I changed the database configuration in config/app.php (just changed the user name and password)

When I ran the project all was good and cakephp page was there.

Now I followed a tutorial from internet and created three file

src/controller/PostsController.php

<?php

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



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

    public function view($id = null) {
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }

        $post = $this->Post->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('post', $post);
    }
}

?>

src/Model/Post.php

<?php

class Post extends AppModel {

}

?>

src/View/Posts/index.ctp

<html>
<body>
<h1>Blog posts</h1>

<?php foreach ($posts as $post): ?>
<p><?php echo $post['Post']['title']; ?> | <?php echo $post['Post']['created']; ?>

<?php endforeach; ?>
<?php unset($post); ?>
    </body>

 </html>

Also I changed 2 lines in config/routes.php

 $routes->connect('/', ['controller' => 'Posts', 'action' => 'index', 'home']);

/**
 * ...and connect the rest of 'Pages' controller's URLs.
 */
$routes->connect('/posts/*', ['controller' => 'Posts', 'action' => 'index']);

When I goto url http://localhost:8888/test/post or http://localhost:8888/test or http://localhost:8888/test/posts

Always I get the error

Error: PostController could not be found.
Error: Create the class PostController below in file: src/Controller/PostController.php
2

There are 2 answers

3
Deepak Nirala On

Make following changes in your Controller:

class PostsController extends AppController {

}
0
eclaude On

Make following changes in your PostsController.php :

namespace App\Controller;
use App\Controller\AppController;

class PostsController extends AppController
{

    public function index()
    {
        $this->set('posts', $this->paginate($this->Posts));
        $this->set('_serialize', ['posts']);
    }

  [...]

}

in your URL try : http://localhost:8888/test/posts