Correct Model And Controller Code Aproach

Hi,

I am considering, where should the following code go: model or controler. Now I have it on model:




public static function getNodes($id)

{

	$records = self::find()

		->where(['parent' => $id])

		->orderBy(['ip' => SORT_ASC, 'mask' => SORT_ASC])

		->asArray()->all();


	$i = 0;

	$nodes = [];


	foreach ($records as $record) 

	{

		$record['mask'] = IPv4Utils::mask2prefix(long2ip($record['mask']));

			

		$nodes[$i] = [

			'data'  => long2ip($record['ip']) . '/' . $record['mask'],

			'attr'  => ['id' => 'node_' .$record['id']],

			'state' =>  $record['hasChild'] ? 'closed' : ''

		];


		$i++;

	}


	return $nodes;

}



Read a lot about MVC, and still I’m frustrated, what goes where.

Should I leave only the query part in model and foreach cycle move to the controller action?

In your model is ok. I know what you’re dealing with, when i started with the MVC design pattern it wasn’t really clear for me as well to what to put where, but you will learn it when you’re working with it a bit longer.

In your controller you ‘catch’ stuff (a request or form data for example) from the user. In your model all the logic is done, so what you want to do with the stuff from the user. And usually if you want (or expect) to use something multiple times, put it in your model.

In your example, you probably want to use the getNodes($id) method more than once, so it’s not logic to put this in your controller, because if you want to use the getNodes($id) again in another controller, you have to write the same(!) function again.

Looks like the model is the best place for this code - since the code is not related to any action or url parameters - but just processing of plain data from your model source.