• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to access CI model in a plain php file?

#1
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
(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
(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


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.