CodeIgniter 4, küçük ve hızlı bir MVC framework'tür. Minimal katmanı sayesinde öğrenmesi kolay, performansı yüksektir. Bu yazıda tam bir CRUD uygulaması kurulur.
Dizin yapısı
app/
├── Controllers/
│ ├── Blog.php
│ └── Home.php
├── Models/
│ └── BlogModel.php
└── Views/
└── blog/
├── index.php
├── form.php
└── show.php
Model
<?php
namespace App\Models;
use CodeIgniter\Model;
class BlogModel extends Model
{
protected $table = 'blogs';
protected $allowedFields = ['title', 'slug', 'content', 'status'];
protected $useTimestamps = true;
public function yayindaki()
{
return $this->where('status', 'published')
->orderBy('published_at', 'DESC')
->findAll();
}
}
Controller
<?php
namespace App\Controllers;
use App\Models\BlogModel;
class Blog extends BaseController
{
public function index()
{
$model = new BlogModel();
return view('blog/index', ['blogs' => $model->yayindaki()]);
}
public function kaydet()
{
$rules = [
'title' => 'required|min_length[5]|max_length[200]',
'content' => 'required',
'status' => 'in_list[published,draft]',
];
if (! $this->validate($rules)) {
return redirect()->back()->withInput()
->with('errors', $this->validator->getErrors());
}
$data = $this->request->getPost();
$data['slug'] = url_title($data['title'], '-', true);
(new BlogModel())->insert($data);
return redirect()->to('/blog')->with('mesaj', 'Yazı kaydedildi.');
}
}
Route tanımı
<?php
// app/Config/Routes.php
$routes->get('/', [Home::class, 'index']);
$routes->get('blog', [Blog::class, 'index']);
$routes->post('blog/kaydet', [Blog::class, 'kaydet']);
View
<?php foreach ($blogs as $blog): ?>
<article>
<h2><a href="/blog/<?= esc($blog['slug']) ?>">
<?= esc($blog['title']) ?>
</a></h2>
<p><?= esc($blog['excerpt']) ?</p>
</article>
<?php endforeach; ?>
CSRF koruması
Formlarda csrf_field(), form açılışında csrf_protect() kullanılır. KodIgniter 4 varsayılan olarak açıktır.
Sonuç
CodeIgniter 4, küçük ekipler ve hızlı teslim gerektiren projeler için idealdir. Katmanları az olduğu için yönlendirme mantığı anlaşılır kalır.
Arivo'da PHP scriptler, temalar ve eklentiler bulun. Kurulum desteği dahil.
Mağazaya Git