- I call the parent constructor as I extend new controllers from
CI_Controller
and MY_Controller
so that I can enjoy higher variable declarations that are shared throughout the project.
- I recommend creating general use model methods so that they have greater utility and can be re-used by many controllers in your project.
- To make it easier to load header data into all controllers in your project, I recommend declaring some default header data in MY_Controller then within lower level controllers, you can amend that data and pass it to the view(s).
ci/application/core/MY_Controller.php
<?php
/**
* @property Listing_model ListingModel
* @property CI_DB_query_builder|CI_DB_postgre_driver $db
* @property CI_Loader $load
* @property CI_Config $config
*/
class MY_Controller extends CI_Controller
{
protected $headerData;
public function __construct()
{
parent::__construct();
$this->headerData['title'] = 'Some Default Title';
$this->headerData['js'] = [
'loaded_unconditionally.js',
];
$this->headerData['css'] = [
'loaded_unconditionally1.css',
'loaded_unconditionally2.css',
];
}
}
ci/application/controllers/Listing.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Listings extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Listings_model', 'ListingsModel');
}
public function show(string $card): void
{
$listing = $this->ListingModel->getByCard($card);
$this->headerData['title'] = $listing->name ?? 'Invalid Card Provided';
$this->load->view('layout/header', $this->headerData);
$this->load->view('listings/listing_card', ['listing' => $listing]);
$this->load->view('layout/footer');
}
}
ci/application/models/Listings_model.php
// returns object or null
function getByCard(string $card): ?object
{
// it is assumed that the slug column will be UNIQUE
return $this->db->get_where('creditcards', ['slug' => $card])->row();
}
// returns empty array or array of objects
function get(?int $limit, int $offset = 0): array
{
$args = ['creditcards'];
if ($limit !== null) {
array_push($args, $limit, $offset);
}
return $this->db->get_where(...$args)->result();
}
ci/application/views/layout/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $title; ?></title>
<?php foreach ($css as $filepath) { ?>
<link rel="stylesheet" href="<?php echo base_url("assets/css/$filepath"); ?>" />
<?php } ?>
<?php foreach ($js as $filepath) { ?>
<script src="<?php echo base_url("assets/js/$filepath"); ?>" />
<?php } ?>
</head>
ci/application/views/listings/listing_card.php
<?php
/**
* @var object|null $listing
*/
// start crafting your html markup and reference $listing as needed
if (!empty($listing->name)) {
echo "<p>Hello $listing->name</p>";
} else {
echo "<p>Um, who are you again?</p>";
}