php/oop/mvc order of operation with markdown files (no db) - php

Goal: understand whether this implemented order/logic of operation indeed belongs to the C part of MVC.
Situation: I have nearly finished a simple note-taking site with markdown files. No database is used except for authentication. The lack of database, however, makes it difficult to know if I am neglecting the M of MVC.
Because I did not want to have the .md extension as part of the pretty url, I am heavily relying on the PageController to settle the order of operation.
From the Controller, PageController inherits the constructed filesystem/Flysystem(fs), twig, and the "$app" that processes any of the three scenarios.
It first checks to see if a param.md exists and then whether param is a directory. If none of the above, then it's a new note. In each case, it uses a corresponding method set by the Application ($app) that processes and returns an array (title, breadcrumbs, content/directory listing, new template etc).
<?php
namespace App\Controller;
class PageController extends Controller {
public function Page($param){
$file=$param.'.md';
if ($this->fs->has($file)) {
$data=$this->app->setNote($file);
return $this->app->render('note.twig',$data)
}
elseif ($this->fs->has($param)) {
$data=$this->app->setFolder($param);
return $this->app->render('folder.twig',$data)
}
else {
$data=$this->app->setNew($param);
return $this->app->render('new.twig',$data)
}
}
}
Per "PHP the Right Way":
Controllers handle the request, process the data returned from models and load views to send in the response.
Although my code works and gets the job done, it does not appear to the be right way because the main App is doing the processing. I guess I could just move the Application.php in the Models folder, but would that make it adhere to "right way"? Should I use a Middleware before the PageController gets to work?
It may seem silly to ask about a code that just works, but my goal is to better understand/learn the current wisdom's ways when dealing with flat-files.

Regardless of whether you are 'database-less', the data is being stored / accessed in the .md files.
Access to them should be abstracted to a Model. You should create a File.find object + method, and/or a File.find_or_create. Then
$file = File.find_or_create($param);
$render_type = $file.type . '.twig';
return $this->app->render($render_type, $file.data);
Put all your if logic in the Model.

Related

Which pattern to use and how to use it when I have Controller, Business Logic, and Repository?

Using MVC I have something like this:
class Controller
{
//returns View
function indexAction()
{
$data = $this->getData($this->id);
$view = new ViewModel();
$view->setVariable('data' => $data);
//used to render HTML template + data above later on
return $view;
}
//gets data from DB
//currently also does business-proprietary computation on data
function getData($id)
{
//repository/dao pattern
$data = $this->repository->getData($id);
//Business Logic "derivation"
foreach ($data as $datum)
{
//that does not go into "Controller
//that does not go into "Repository"
//but where does it go? - that's my question
$derivedData[] = (new Business())->doLogic($datum);
}
return $derivedData;
}
}
Recap
I used Controller to get my data out of DB using Repository pattern, then placed received data into view. But business-related computations are left stranded.
Question
Where do I place my business logic computations that act on the data gotten from repository? The derived data which is to return to Controller later, to be placed into View?
My personal choices of architecture are usually to:
Have small controllers as thin as I can, doing only session and general right checking
Services that are handling all business logic, one (one classe yes) per potential feature I need
Services are querying repositories, and eventually manipulate the data in and out, but usually no Controller, nor view will do a ->save() anywhere.
This means that those services are usually designed to be independent from the database and easier to be tested because they only take care of one and only one task.
In your example, the whole function getData will be a service that I would call GetCarDataById. This assuming that you manipulate Cars, I don't like to leave data wandering alone.
EDIT: to make it clear, this kind of approach is not MVC to some definition, most people interpret MVC as putting all code either in controller, either in repositories (model). To others view, MVC doesn't mean that you have other classes, what I call services, and actually most of my code lives here.
The MVC pattern is clear for me.
From wikipedia:
The model directly manages the data, logic and rules of the
application. A view can be any output representation of information,
such as a chart or a diagram. Multiple views of the same information
are possible, such as a bar chart for management and a tabular view
for accountants. The third part, the controller, accepts input and
converts it to commands for the model or view.
Answering your question. The modifications goes in the model domain.

Which MVC thing I need here?

In general there are ActionController, Repositories, Models und Views in TYPO3 Flows domain driven MVC system. In our project we use a general File model that contains the Ressource.
Now we need a special "expert" php script like an action controller that doesn't listen to certain url actions. It should get such a File object, do something internal like logging stuff or manipulate the object after a special procedure and give back an information / return falue.
What mvc thing I need for that? An interface? A manager? How you call that and how do I initialise it in TYPO3 Flow? Or is the FileController (action controller) exact the thing I have to use for that?
This "expert" shouldn't listen to url actions but should be used like an action controller like
$expertyThing = new ../../Expertything();
$expertyThing->doCoolStuff($file);
and should can use thinks like the PersistenceManager (by injection or anyhow).
Thanks for any input for that.
I would say Service but I'm not sure if I understood you correctly.
I guess you have some FileController and you have createFileAction there, which creates new File model from uploaded resource, do some validation, transformations, renaming and save it using injected FileRepository.. And you want something in middle.
So I create FileService for that My/FileManager/Domain/Service/FileService.php - inject repository and other services there. And in action or command controllers I inject those services and they do "expert" stuff (and I don't have to duplicate code), like that:
// FileController
public function createFileAction(Resource $resource) {
try {
$file = $this->fileService->processAndSaveFile($resource);
} catch (\Exception $e) {
$this->addFlashMessage($e->getMessage(), '', Message::SEVERITY_ERROR);
$this->forwardToReferringRequest();
}
$this->addFlashMessage('File created');
$this->redirect('fileList');
}
So for me FileService do expert stuff for File - it creates new File model (maybe using FileFactory), do transformations using other services like ImageService, has repository and logger injected (but you can use Aspects for cases like logging).. and if something goes wrong it throws some FileException.
And of course FileService may implement some FileServiceInterface, and you can inject this interface to your controller and define in Objects.yaml which service should be used (it makes it more flexible, so someone else could implement it and replace your FileService not touching it).
This "Service" approach may be a little bit outdated, so maybe someone will suggest better solution.. If you want follow Flow rules, just check how they handle stuff like that in official packages.

MVC: what code belongs to the model

I've started development on a CakePHP project since a few weeks now. Since the beginning I was struggling with the amount of code inside the controllers. The controllers have, in most cases more lines of code than the models. By knowing the expression "Skinny controller, fat model" I'm searching for some days now for a way to put more code in the models.
The question arises at this point is, "where to draw the line". What should the controller do and what should the model do. There are already some questions/answers on this only I'm searching for a more practical explanation. For example I've put a function below which is now inside the controller. I think a part of this code must and can be moved to the model. So my question is: what part can I move to the model and what can remain in the controller.
/**
* Save the newly added contacts and family members.
*/
public function complete_contacts()
{
if ($this->request->is('post')) {
if (isset($this->data['FamilyMembers'])) {
$selected_user = $this->Session->read('selected_user');
$family_members = $this->data['FamilyMembers'];
$this->ContactsConnection->create();
foreach ($family_members as $family_member) {
// connection from current user to new user
$family_member['ContactsConnection']['contact_family_member_id'] = $selected_user['id'];
$family_member['ContactsConnection']['nickname'] = $selected_user['first_name'];
$this->ContactsConnection->saveAll($family_member);
// inverted connection from new user to current user
$inverted_connection['ContactsConnection']['family_member_id'] = $selected_user['id'];
$inverted_connection['ContactsConnection']['contact_family_member_id'] = $this->FamilyMember->inserted_id;
$inverted_connection['ContactsConnection']['nickname'] = $family_member['FamilyMember']['nickname'];
$this->ContactsConnection->saveAll($inverted_connection);
}
}
}
}
Should I create a function in the FamilyMember model called: "save_new_family_member($family_member, $selected_user)"?
As far as the purposes of the M and the C
The model manages the behavior and data of the application domain,
responds to requests for information about its state (usually from the
view), and responds to instructions to change state (usually from the
controller).
The controller receives user input and initiates a response by making
calls on model objects. A controller accepts input from the user and
instructs the model and a view port to perform actions based on that
input.
I would suggest you can pass
$selected_user = $this->Session->read('selected_user');
To your Model and perform your for each inside of your Model. You may want to change rules as to how the data is stored or perform some transformations on it and the Controller should be blind to this. Basically use the Controller to get your information [from the View often] to the Model. Don't directly manipulate the Model from the Controller. In short YES create the function that you suggested :)
That being said sometimes I find myself in a position where my Controller has to do more than I'd like, in which case at least break the task down into helper methods that way your controller is more manageable and you can reuse code where needed.
You are doing it right.
You can of course create some methods in model and make it fat with:
function updateContactFamilyMemberId($id){}
function updateNickname($nickname){}
...
In my opinion it still will be correct, but unnecessary.

Admin panel - what is the best way to display "static" data in the layout?

I'm about to write a admin panel for my CMS written in CodeIgniter. There will be some user information visible at all time - both in the layout's header section and the sidebar. I'm used to do it in a way that I personally hope and think could be done a lot easier, since I'm tired of sending the same parametres to the view over and over again, when it's dynamic data that needs to be displayed on every page anyways (such as unread messages, username, name, status, etc).
I'll need controllers and models, I know that, but do I have to pass, just for an example, the user's username, unread messages etc. every time I need to load a view? Should I do some kind of library for this?
Now my question is: How would I do it when it comes to best practice and for making it easy to maintain in the future?
I hope my question is understandable :)
Personally, I would extend the Controller library (create a MY_Controller by following the guidance at the bottom of Creating Libraries at codeigniter.com).
You would use your model etc as normal. Then you would create a private function in your MY_Controller class to get the relevant "global" data and call
$this->load->vars('everywhere_data', $data_from_relevant_models);
which would make the data available to all views called from that point on as $everywhere_data. Then add a reference to that function in the constructor of MY_Controller, perhaps with a conditional checking for the user to be actually logged in.
If it's complex to collect and get all that data, you might write a library to handle it for you, but the 'controller' part would still be done by MY_Controller: i.e. to get the data and then use load->vars() to publish it to the view.
As a quick and untested example, MY_Controller would start something like as follows:
<?php
class MY_Controller extends Controller
{
private $logged_in_user;
function MY_Controller()
{
parent::Controller();
if( $this->_logged_in_userid() > 0 )
{
$this->logged_in_user = $this->_get_user( $this->logged_in_userid() );
$this->load->vars('logged_in_username', $this->logged_in_user->username );
} else {
$this->logged_in_user = false;
}
}
...
}
Note that things like _logged_in_userid() would access the session for you (e.g. return $this->session->userdata('logged_in_userid');), and _get_user() would access the relevant models.
Finally, you would have a view that accesses $logged_in_username (or everywhere_data in my first example) which you would call into your headers etc. This leaves your normal controllers uncluttered so that they can focus on delivering their specific functionality, stops you rewriting your code several times AND maintains the MVC ideals.
You could create a View just to hold the information and get it from a $_SESSION variable in the View itself if you want to keep it all in one place.

Is it a good idea to allow the router to look up controllers from a database?

In most of the tutorials for PHP MVC design structures, a router class is used to take user input and look up the right controller in order to process that input accurately. The input normally takes the form of a url. For example http://example.com/foo/bar/ would ask the router to find the controller named foo and fire the method bar.
PHP also has an auto-include function which requires a consistent naming system to used for your classes. For example, if I wanted to get an instance of the class Foo, I would need the file to be called Foo.php and inside would be a class called Foo.
Unfortunately, in tandem, these mechanisms place competing demands on the naming system. The url is very 'front facing' and as such, clients will often need it to reflect the content of a particular page. For example, if I have a page that gives directions to a venue, the client may need this page to be at http://example.com/venues/directions/. Later the content may change and the number of venues is reduced to 1 and now the client wishes the url to read http://example.com/venue/directions/. Obviously, this is a very trivial example but I think the need to change urls occasionally is clear.
Since the urls are very tightly connected to the controller classes, a change to a url means the class file name, the class name itself and any instances of that class will all require changing. For more complex systems this seems very time consuming, to me.
What sort of solutions are there to this problem? It seems to me that a directory of sorts will be necessary in which relations between urls and controllers are stored such that any url could be used to call any controller regardless of what either is named. Thus we would have a venues controller and a venues url and when the client requests a change in the url, we just make a change in the directory translating the new "venue" into "venues".
I think the best way to do this would be in a database table but this then requires an extra query for every user request. Is a database the right way to implement a directory? Is a directory even the best way to solve the above problem? Is this problem even a problem in the first place???
Some solutions I have seen to this is to explicitly specify a routing "connection" to a controller/action.
For example, in NiceDog, you can specify routes like
R('venues?/directions')
->controller('VenueController')
->action('directionsAction')
->on('GET');
Allowing a regular expression to match the URL. (The expression above will match venue/directions or venues/directions) I like this method, because it decouples the controller naming scheme from the URL naming scheme.
Another more configuration-based approach would be to have some kind of explicit mapping:
$routes = array(
'venues?' =>
array('controller'=>'VenueController','action'=>'indexAction'),
'venues?/directions' =>
array('controller'=>'VenueController','action'=>'directionsAction')
);
And then a simple dispatch function:
function dispatch($url,$routes) {
foreach ($routes as $pattern=>$map) {
if (preg_match($pattern,$url,$matches)) {
$controller = new $map['controller']();
$action = $map['action'];
call_user_func_array(
array($controller,$action),
array_slice($matches,1)
);
return true;
}
}
throw new Exception('Route not found.');
}
A good way to solve this problem is for the MVC framework to allow you to specify your own routing rules. For example, see URI Routing in the CodeIgniter framework's documentation.
To go along with your example, this would allow you to remap requests for /venues/ to /venue.

Categories