Answer the question
In order to leave comments, you need to log in
What is the correct way to pass optional POST parameters to the model?
I'm making a small blog site in PHP. I made the architect based on this article - https://habrahabr.ru/post/150267/.
To the point: The model method that returns articles from the database takes two optional arguments - page number and the number of articles per page.
As I understand it, the processing of GET and POST arrays should be in the controller. And how is it more correct to implement a check for the existence of variables and, based on their presence / absence, call the model method with the necessary parameters?
Two options come to mind:
1 - Check for availability, and based on the result, call the method without parameters / with one parameter / with parameters
2 - If the variables are not set, fill them with standard values in the controller constructor.
Model method:
public function get_data($articles_pp = 2, $page = 1)
{
$pdo = self::connect();
for($i=($articles_pp*$page); $i>=$page*$articles_pp-($articles_pp-1); $i--)
{
$data = $pdo->query('SELECT * FROM articles WHERE id = '.$i);
$return_arr[$i] = $data->fetch();
}
return $return_arr;
}
public $articles_pp;
public $page;
function __construct()
{
$this->model = new Model_Main();
$this->view = new View();
//if(isset($_POST['page'])) $this->page = $_GET['page'];
$this->page = $_GET['page'];
$this->articles_pp = $_GET['articles_pp'];
}
function action_index()
{
$data = $this->model->get_data($this->articles_pp, $this->page);
$this->view->generate('main_view.php', 'template_view.php', $data);
}
Answer the question
In order to leave comments, you need to log in
A strange request to select from the database - why send a request for each article? You can select all articles through LIMIT and OFFSET.
On the question - option 2
If there are no optional parameters, we replace them with default values and pass them to the model.
And it is better to remove receiving parameters from the constructor. often controller action methods have different set of parameters.
in controller model and view binding, validation in model.
but in general, the anipatern now rules, you give the orm model stuffed with data directly into the view and right in the route :)
$data = \App\Models\Data::orderBy('name')
->approved()
->paginate(4, ['*'], 'page', $page);
return view('data', compact('data'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question