Welcome Guest, Not a member yet? Register   Sign In
How to access CI model in a plain php file?
#1

(This post was last modified: 10-16-2018, 07:41 AM by happyape.)

I have file at this location of my CI4 project
Code:
CI4/public/star/ratings.php

My model file is at
Code:
CI4/Application/Models/StarModel.php

Is it possible to access this Model in the ratings.php?

I tried

Code:
<?php
use App\Models\StarModel;
$starmodel = new StarModel();
?>

I expected it not to work and it didn't. I know I need to get the namespace structure right. What's the correct way? Thanks
Reply
#2

Did you try to include the model?
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

If ratings.php is a class make it Ratings.php and put it in the Libraries folder and namespace it like:

<?php namespace App\Libraries;
use App\Models\StarModel;

class Ratings {
protected $starModel;

public function __construct() {
$starmodel = new StarModel();
}
}
Simpler is always better
Reply
#4

(This post was last modified: 10-16-2018, 09:50 AM by happyape.)

(10-16-2018, 08:30 AM)InsiteFX Wrote: Did you try to include the model?

Did you mean include e.g. include_once dirname(dirname(dirname(dirname(__FILE__)))).'/application/Models/StarModel.php';

It gives me this error -
Code:
Fatal error: Class 'CodeIgniter\Model' not found in .../Models/StarModel.php

I think I just have to figure out how to set a psr-4 in composer somewhere as this file is outside Application folder i.e. inside Public/star/ratings.php
Reply
#5

(10-16-2018, 09:26 AM)donpwinston Wrote: If ratings.php is a class make it Ratings.php and put it in the Libraries folder and namespace it like:

<?php namespace App\Libraries;
use App\Models\StarModel;

class Ratings {
   protected $starModel;

   public function __construct() {
       $starmodel = new StarModel();
   }
}

No - It's not a class but just contains very little code. The problem with moving to inside Application folder is I won't be able to access it directly e.g mydomain/star/ratings.php. I can easily duplicate the methods inside my model but that's what I am trying to avoid if possible.
Reply
#6

(This post was last modified: 10-16-2018, 09:37 PM by sv3tli0.)

(10-16-2018, 09:45 AM)happyape Wrote: No - It's not a class but just contains very little code. The problem with moving to inside Application folder is I won't be able to access it directly e.g mydomain/star/ratings.php. I can easily duplicate the methods inside my model but that's what I am trying to avoid if possible.

You should not access any class / code directly !! For that you have routes to controllers !

Make your Library where it should be then just add 1 controller / action which will be called it on specific url ...

In other case why the hell you use CI if you don't care of it's structure ?
Best VPS Hosting : Digital Ocean
Reply




Theme © iAndrew 2016 - Forum software by © MyBB