Eloquent cannot find Code Igniter Model - codeigniter

So I am using Eloquent with code igniter and getting some interesting bugs.
class Brand_model extends MY_Model {
public function size()
{
return $this->hasOne('Size');
}
}
That line errors when trying to load my Size model:
class Size extends MY_Model {
public function brand(){
return $this->belongsTo('Brand');
}
}
"Unable to find class Size"
Any ideas?

you can try adding autoload part, to your composer.json file, like here: http://snipr.it/~Dh
Then tun php composer.phar dumpautoload, it will load models from specified directories
After this, classes should be found.
Other option is just do $this->load->model('Brand_model'); $this->load->model('size');
Try both, hope it helps!

You need to make sure that you loaded the composer autoload in your index file.
Please check out the full sample at CodeIgniter_with_Eloquent
Insert the code below right before the last line in your index.php:
require_once './vendor/autoload.php';
Hope it helped!

Related

How to work with subdirectory controllers in CodeIgniter 4?

I need help with using sub directory controllers in CodeIgniter 4.
I just can't make it work for some reason.
This is the URL for example: www.example.com/admin/dashboard
In the controllers folder, I created a folder named Admin, and a file named Dashboard.php.
I used this code in Dashboard.php:
namespace App\Controllers;
class Dashboard extends BaseController
{
public function index()
{
}
}
I tried changing the class name to AdminDashboard, Admin_Dashboard, pretty much every logical name but every time I get a 404 error, saying:
Controller or its method is not found:
App\Controllers\Admin\Dashboard::index
I know the file itself gets loaded successfully, but I think I don't declare the classname correctly and it keeps throwing me those 404 errors.
The documentation of CI4 isn't providing any information about what the classname should be called unfortunately...
UPDATE #1
I managed to make it work by changing few things:
namespace App\Controllers\Admin;
use CodeIgniter\Controller;
class Dashboard extends Controller
{
public function index()
{
}
}
But now it won't extend the BaseController which has some core functions that I built for my app.
Any ideas to how to make it extend BaseController?
I must admit that I don't have much knowledge about namespacing yet, so that might be the reason for my mistakes.
As I imagined, the problem was that I didn't learn about namespacing.
I needed to point the use line at the BaseController location.
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
class Dashboard extends BaseController
{
public function index()
{
}
}
Now www.example.com/admin/dashboard/ goes directly to that index function, as intended.
php spark make:controller /Subfolder/ControllerName
$routes->add('/(.+?)_(.+?)/(.+?)$', 'subdir\\\\$1_$2::$3');
$routes->add('/(.+?)_(.+?)$', 'subdir\\\\$1_$2::index');
I was able to map with this setting.
The route mapping could be as simple as:
$routes->group('admin', static function ($routes) {
$routes->get('dashboard', 'Admin\Dashboard::index');
});

Laravel Newbie: model Class Not Found in routes.php

Creating my first model with Laravel and its stored at app/models/Login.php. It is:
class Login extends Eloquent {
public $timestamps = false;
}
In a Route in routes.php I am getting a Class 'Login' not found on the line $logins = Login::all();
I have run composer dump-auto in the root of the application (above app) and confirmed that the composer.json file contains "app/models", in the autoload classmap.
Thanks!
EDIT
Adding the Route (never mind that it doesn't actually use num yet):
Route::get('/logins/last/{num}', function($num)
{
$logins = Login::all();
return View::make ('logins.last.index')
->with('logins', $logins)
->with('num', $num);
})->where('num', '[0-9]+'
);
Wrap you code with <?php and ?> tags, which tell PHP to start and stop interpreting the code.

Laravel 4 model unit test with Codeception - Class 'Eloquent' not found

I'm trying to use Codeception to run my Laravel 4 unit tests.
Running a test for a simple class with no dependencies works fine. But when I instantiate a model which depends on Eloquent, I get this fatal error:
PHP Fatal error: Class 'Eloquent' not found in /var/www/project/app/models/Role.php on line 4
Unit test:
<?php
use Codeception\Util\Stub;
class TestModel extends \Codeception\TestCase\Test
{
public function testExample()
{
$role = new Role;
$role->name = 'superuser';
$this->assertEquals('superuser', $role->name);
}
}
Model:
<?php
class Role extends Eloquent
{
public function users()
{
return $this->belongsToMany('User');
}
}
Project structure:
I'm running vendor/bin/codecept run unit from the project root, with this file structure:
/project
codeception.yml
/vendor/bin/codecept
/app
/tests
unit.suite.yml
/unit
ExampleTest.php
/models
Role.php
...etc
What am I doing wrong?
By looking at the Codeception L4 sample app, I was able to see how to bootstrap the autoload to resolve this issue, by adding these lines to project/app/tests/_boostrap.php:
include __DIR__.'/../../vendor/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/start.php';
\Codeception\Util\Autoload::registerSuffix('Page', __DIR__.DIRECTORY_SEPARATOR.'_pages');
Edit: when upgrading from Laravel 4.0 to 4.1, it is also necessary to add an extra line:
$app->boot();
I'm probably late to the party, but if you don't need the codecept stuff. You should be extending laravel's implementation of PHPUnit_Framework_TestCase called just TestCase. Like this:
class TestModel extends TestCase {
}
The answer to this question is a little outdated now. With Laravel 5 I got the same error (Class 'Eloquent' not found...) and solved it by copying the code from Laravels base TestCase.php file. This file is used for testing within the Laravel framework (NOT using codeception).
To fix the 'Eloquent not found' error, add the following lines to project/tests/unit/_bootstrap.php
<?php
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
Honestly I'm not sure why it works, but it does! I'll edit if I figure out why or someone comments.
The Eloquent class cannot be found when you are running your unit tests.
Try adding use Illuminate\Database\Eloquent\Model as Eloquent; to Role.php.
You can go to TestCase class and override method refreshApplication (add method to TestCase) with adding auth or some:
protected function refreshApplication()
{
$this->app = $this->createApplication();
$this->client = $this->createClient();
$this->app->setRequestForConsoleEnvironment();
$this->app->boot();
// authenticate your user here, when app is ready
$user = new User(array('username' => 'John', 'password' => 'test'));
$this->be($user);
}
I solved a similar problem with Laravel 4 and Codeception by adding the following lines to _bootstrap.php
$app = require __DIR__.'/../../bootstrap/start.php';
$app->boot();
Hope this helps a fellow googler!

How to register a namespace in laravel 4

The problem:
class PostRepostioryInterface not found for line 4 in PostController.php
or in tinkering with the namespace I've even got class
App\Models\Interfaces\PostRepositoryInterface not found
The questions: How to register a namespace in laravel 4? What do I need to do to get L4 to recognise the classes/interfaces at this namespace?
Larave 3 had a $namespaces static object in ClassLoader where you could add namespaces by
Autoloader::namespaces(array(
'App\Models\Interfaces' => path('app').'models/interfaces',
));
I'm not sure if I have that right for laravel 3 but either way, AutoLoader doesn't exist in Laravel 4 and ClassLoader exists but the method namespaces doesn't exist in ClassLoader in Laravel 4.
I've looked at this but it doesn't seem to work without registering the namespace somehow.
Using namespaces in Laravel 4
Example structure:
app/models/interfaces
PostRepostitoryInterface.php
app/models/repositories
EloquentPostRepository.php
namespaces:
App\Models\Repositories;
App\Models\Interfaces;
the files:
PostRepositoryInterface.php
<?php namespace App\Models\Interfaces;
interface PostRepositoryInterface {
public function all();
public function find($id);
public function store($data);
}
EloquentPostRepository.php
<?php namespace App\Models\Repositories;
use App\Models\Interfaces\PostRepositoryInterface;
class EloquentPostRepository implements PostRepositoryInterface {
public function all()
{
return Post::all();
}
public function find($id)
{
return Post::find($id);
}
public function store($data)
{
return Post::save($data);
}
}
PostController.php
<?php
use App\Models\Interfaces\PostRepositoryInterface;
class PostsController extends BaseController {
public function __construct( PostRepositoryInterface $posts )
{
$this->posts = $posts;
}
Thanks
You probably forgot to do composer dump-autoload. This updates the list of classes Laravel autoloads.
You can read more on composer documentation.
On the laravel irc channel I found out the namespaces should work in L4 without a need for registering them anywhere. This is because the composer dump-autoload adds them to the composer/autoload file for me. So that was not an issue.
The issue turned out to be a typo apparently(I can't find it in the code above but after going through every line copy/pasting the class names and namespaces something changed), and also somehow in my real code I left out the 'use' statement for EloquentPostRepository.php
use App\Models\Interfaces\PostRepositoryInterface;
Now I've hit another wall trying to use the namespaced interface with ioc and the controller constructor (target interface App\Models\Interfaces\PostRepositoryInterface is not instantiable) but I guess that should be a different question.

Beginners Tutorial for Zend Framework implementing model and call it from Controller

I'm quite new to ZF, and right now, i try to write a tiny app, based on ZF. It works more or less fine until now. I wanna access my db- data. For starters, i just want to use query-string, before I start messing araound with zend_db. So to keep a nice mvc-structure, I created application/models/IndexMapper.php
class Application_Models_IndexMapper{...}
it just contains one function by now to see if it works
public function test(){
return ('yay');
}
In my IndexController, which is working, i try to access my model by
$indexMapper = new Application_Models_IndexMapper();
$x = $indexMapper->test();
but the first line throws an
Fatal error: Class 'Application_Models_IndexMapper' not found in /path/to/application/controllers/IndexController.php on line 31
As I'm new, I don't understand the more complex tutorials and they don't help me fix my problem. What am I doing wrong? Do I have to include it somehow?
Thanks
edit: my application/bootstrap.php
<?php
defined('APPLICATION_PATH')
or define('APPLICATION_PATH' , dirname(__FILE__));
defined('APPLICATION_ENVIRONMENT')
or define('APPLICATION_ENVIRONMENT' , 'development');
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
$frontController = Zend_Controller_Front::getInstance();
$frontController->setControllerDirectory(APPLICATION_PATH . '/controllers');
$frontController->setParam('env', APPLICATION_ENVIRONMENT);
Zend_Layout::startMvc(APPLICATION_PATH . '/layouts/scripts');
//Doctype
$view = Zend_Layout::getMvcInstance()->getView();
$view->doctype('HTML5');
$view->addHelperPath('App/View/Helper', 'App_View_Helper');
unset($frontController);
The structure for a model would be found under ./application/models/IndexMapper.php. In that file you would have the class As you named it and then the autoloading will work.
A great beginner tutorial would be found on www.akrabat.com
You have your class in the wrong place and have named it incorrectly.
Your class should be in application/models/Indexmapper.php and should look like this:-
class Application_Model_Indexmapper
{
public function test(){
return ('yay');
}
}
Then you call it thus:-
$indexMapper = new Application_Model_Indexmapper();
$x = $indexMapper->test();
Notice I dropped the 's' from the end of Models, it is not required and will cause an error as you found. Also the class is in the models folder, not modules. If you want to use modules then you need to read this and this from the manual.
Your bootstrap.php should look like this for a first, basic project:-
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
//Yes, it's empty!
}
Well, I guess my tutorial wasn't very helpful. I'll do as recommended, and start over from scratch. Thanks though

Resources