# Tutorial - Basic - - - ## Overview Throughout this tutorial, we will create an application with a simple registration form, while introducing the main design aspects of Phalcon. This tutorial covers the implementation of a simple MVC application, showing how fast and easy it can be done with Phalcon. Once developed, you can use this application and extend it to suit your needs. The code in this tutorial can also be used as a playground to learn other Phalcon specific concepts and ideas. If you just want to get started you can skip this and create a Phalcon project automatically with our [developer tools][devtools]. The best way to use this guide is to follow along and try to have fun. You can get the complete code [here][github_tutorial]. If you get stuck or have questions, please visit us on [Discord][discord] or in our [Discussions][discussions]. ## File Structure One of the key features of Phalcon is that it is loosely coupled. Because of that, you can use any directory structure that is convenient to you. In this tutorial we will use a _standard_ directory structure, commonly used in MVC applications. ```text . └── tutorial ├── app │ ├── controllers │ │ ├── IndexController.php │ │ └── SignupController.php │ ├── models │ │ └── Users.php │ └── views └── public ├── css ├── img ├── index.php └── js ``` !!! warning "NOTE" Since all the code that Phalcon exposes is encapsulated in the extension (that you have loaded on your web server), you will not see `vendor` directory containing Phalcon code. Everything you need is in memory. If you have not installed the application yet, head over to the [installation][installation] page and complete the installation prior to continuing with this tutorial. If this is all brand new it is recommended that you install the [Phalcon Devtools][devtools] also. The DevTools leverage PHP's built-in web server, allowing you to run your application almost immediately. If you choose this option, you will need a `.htrouter.php` file at the root of your project with the following contents: ```php setDirectories( [ APP_PATH . '/controllers/', APP_PATH . '/models/', ] ); $loader->register(); ``` ### Dependency Management Since Phalcon is loosely coupled, services are registered with the frameworks Dependency Manager, so they can be injected automatically to components and services wrapped in the [IoC][ioc] container. Frequently you will encounter the term DI which stands for Dependency Injection. Dependency Injection and Inversion of Control(IoC) may sound complex but Phalcon ensures that their use is simple, practical and efficient. Phalcon's IoC container consists of the following concepts: - Service Container: a "bag" where we globally store the services that our application needs to function. - Service or Component: Data processing object which will be injected into components Each time the framework requires a component or service, it will ask the container using an agreed upon name for the service. This way we have an easy way to retrieve objects necessary for our application, such as the logger, database connection etc. !!! warning "NOTE" If you are still interested in the details please see this article by [Martin Fowler][injection]. Also, we have [a great tutorial][di] covering many use cases. ### Factory Default The [Phalcon\Di\FactoryDefault][di-factorydefault] is a variant of [Phalcon\Di\Di][di]. To make things easier, it will automatically register most of the components that are required by an application and come with Phalcon as standard. Although it is recommended to set up services manually, you can use the [Phalcon\Di\FactoryDefault][di-factorydefault] container initially and later on customize it to fit your needs. Services can be registered in several ways, but for our tutorial, we will use an [anonymous function][anonymous_function]: `public/index.php` ```php set( 'view', function () { $view = new View(); $view->setViewsDir(APP_PATH . '/views/'); return $view; } ); ``` Now we need to register a base URI, that will offer the functionality to create all URIs by Phalcon. The component will ensure that whether you run your application through the top directory or a subdirectory, all your URIs will be correct. For this tutorial our base path is `/`. This will become important later on in this tutorial when we use the class `Phalcon\Tag` to generate hyperlinks. `public/index.php` ```php set( 'url', function () { $url = new Url(); $url->setBaseUri('/'); return $url; } ); ``` ### Handling the Application Request In order to handle any requests, the [Phalcon\Mvc\Application][application] object is used to do all the heavy lifting for us. The component will accept the request by the user, detect the routes and dispatch the controller and render the view returning the results. `public/index.php` ```php handle( $_SERVER["REQUEST_URI"] ); $response->send(); ``` ### Putting Everything Together The `tutorial/public/index.php` file should look like: `public/index.php` ```php registerDirs( [ APP_PATH . '/controllers/', APP_PATH . '/models/', ] ); $loader->register(); $container = new FactoryDefault(); $container->set( 'view', function () { $view = new View(); $view->setViewsDir(APP_PATH . '/views/'); return $view; } ); $container->set( 'url', function () { $url = new Url(); $url->setBaseUri('/'); return $url; } ); $application = new Application($container); try { // Handle the request $response = $application->handle( $_SERVER["REQUEST_URI"] ); $response->send(); } catch (\Exception $e) { echo 'Exception: ', $e->getMessage(); } ``` !!! info "NOTE" In the tutorial files from our [GitHub][github_tutorial] repository, to register services in the `DI` container, we use the array notation i.e. `$container['url'] = ....`. As you can see, the bootstrap file is very short, and we do not need to include any additional files. You are well on your way to creating a flexible MVC application in less than 30 lines of code. ## Creating a Controller By default, Phalcon will look for a controller named `IndexController`. It is the starting point when no controller or action has been added in the request (e.g. `https://localhost/`). An `IndexController` and its `IndexAction` should resemble the following example: `app/controllers/IndexController.php` ```php Hello!'; } } ``` The controller classes must have the suffix `Controller` and controller actions must have the suffix `Action`. For more information you can read our document about [controllers][controllers]. If you access the application from your browser, you should see something like this: ![](assets/images/content/tutorial-basic-1.png) !!! success "NOTE" **Congratulations, you are Phlying with Phalcon!** ## Sending Output to a View Sending output to the screen from the controller is at times necessary but not desirable as most purists in the MVC community will attest. Everything must be passed to the view that is responsible for outputting data on screen. Phalcon will look for a view with the same name as the last executed action inside a directory named as the last executed controller. Therefore, in our case if the URL is: ```php http://localhost/ ``` will invoke the `IndexController` and `indexAction`, and it will search the view: ```php /views/index/index.phtml ``` If found it will parse it and send the output on screen. Our view then will have the following contents: `app/views/index/index.phtml` ```php Hello!"; ``` and since we moved the `echo` from our controller action to the view, it will be empty now: `app/controllers/IndexController.php` ```php Hello!"; echo PHP_EOL; echo PHP_EOL; echo $this->tag->a('signup', 'Sign Up Here!'); ``` The generated HTML code displays an anchor (``) HTML tag linking to a new controller: `app/views/index/index.phtml` (rendered) ```html

Hello!

Sign Up Here! ``` To generate the link for the `` tag, we use the [Phalcon\Html\TagFactory][html-tagfactory] component. This is a utility class that offers an easy way to build HTML tags with framework conventions in mind. This class is also a service registered in the Dependency Injector, so we can use `$this->tag` to access its functionality. !!! info "NOTE" `Phalcon\Html\TagFactory` is already registered in the DI container since we have used the `Phalcon\Di\FactoryDefault` container. If you registered all the services on your own, you will need to register this component in your container to make it available in your application. ![](assets/images/content/tutorial-basic-2.png) And the Signup controller is (`app/controllers/SignupController.php`): `app/controllers/SignupController.php` ```php Sign up using this form tag->form("signup/register"); ?>

tag->textField("name"); ?>

tag->textField("email"); ?>

tag->submitButton("Register"); ?>

``` Viewing the form in your browser will display the following: ![](assets/images/content/tutorial-basic-3.png) As mentioned above, the [Phalcon\Html\TagFactory][html-tagfactory] utility class, exposes useful methods allowing you to build form HTML elements with ease. The `form()` method receives an array of key/value pairs that set up the form, for example a relative URI to a controller/action in the application. The `inputText()` creates a text HTML element with the name as the passed parameter, while the `inputSubmit()` creates a submit HTML button. Finally, a call to `close()` will close our `
` tag. By clicking the _Register_ button, you will notice an exception thrown from the framework, indicating that we are missing the `register` action in the controller `signup`. Our `public/index.php` file throws this exception: ```bash Exception: Action "register" was not found on handler "signup" ``` Implementing that method will remove the exception: `app/controllers/SignupController.php` ```php set( 'db', function () { return new Mysql( [ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'secret', 'dbname' => 'tutorial', ] ); } ); ``` Adjust the code snippet above as appropriate for your database. With the correct database parameters, our model is ready to interact with the rest of the application, so we can save the user's input. First, let's take a moment and create a view for `SignupController::registerAction()` that will display a message letting the user know the outcome of the _save_ operation. `app/views/signup/register.phtml` ```php
tag->a('/', 'Go back', ['class' => 'btn btn-primary']); ?> ``` Note that we have added some css styling in the code above. We will cover including the stylesheet in the [Styling][styling] section below. ## Storing Data using Models `app/controllers/SignupController.php` ```php request->getPost(); // Store and check for errors $user = new Users(); $user->name = $post['name']; $user->email = $post['email']; // Store and check for errors $success = $user->save(); // passing the result to the view $this->view->success = $success; if ($success) { $message = "Thanks for registering!"; } else { $message = "Sorry, the following problems were generated:
" . implode('
', $user->getMessages()); } // passing a message to the view $this->view->message = $message; } } ``` At the beginning of the `registerAction` we create an empty user object using the `Users` class we created earlier. We will use this class to manage the record of a user. As mentioned above, the class's public properties map to the fields of the `users` table in our database. Setting the relevant values in the new record and calling `save()` will store the data in the database for that record. The `save()` method returns a `boolean` value which indicates whether the save was successful or not. The ORM will automatically escape the input preventing SQL injections, so we only need to pass the request to the `save()` method. Additional validation happens automatically on fields that are defined as not null (required). If we do not enter any of the required fields in the sign-up form our screen will look like this: ![](assets/images/content/tutorial-basic-4.png) ## List the Registered Users Now we will need to get and display all the registered users in our database The first thing that we are going to do in our `indexAction` of the` IndexController` is to show the result of the search of all the users, which is done simply by calling the static method `find()` on our model (`Users::find()`). `indexAction` would change as follows: `app/controllers/IndexController.php` ```php view->users = Users::find(); } } ``` !!! info "NOTE" We assign the results of the `find` to a magic property on the `view` object. This sets this variable with the assigned data and makes it available in our view In our view file `views/index/index.phtml` we can use the `$users` variable as follows: The view will look like this: `views/index/index.phtml` ```html Hello!"; echo $this->tag->a('signup', 'Sign Up Here!', ['class' => 'btn btn-primary']); if ($users->count() > 0) { ?>
# Name Email
Users quantity: count(); ?>
id; ?> name; ?> email; ?>
Phalcon Tutorial
getContent(); ?>
``` In the above template, the most important line is the call to the `getContent()` method. This method returns all the content that has been generated from our view. Our application will now show: ![](assets/images/content/tutorial-basic-6.png) ## Conclusion As you can see, it is easy to start building an application using Phalcon. Because Phalcon is an extension loaded in memory, the footprint of your project will be minimal, while at the same time you will enjoy a nice performance boost. If you are ready to learn more check out the [Vökuró Tutorial][tutorial-vokuro] next. [anonymous_function]: https://php.net/manual/en/functions.anonymous.php [discord]: https://phalcon.io/discord [discussions]: https://phalcon.io/discussions [github_tutorial]: https://github.com/phalcon/tutorial [htrouter]: https://github.com/phalcon/phalcon-devtools/blob/master/templates/.htrouter.php [injection]: https://martinfowler.com/articles/injection.html [ioc]: https://en.wikipedia.org/wiki/Inversion_of_control [psr-4]: https://www.php-fig.org/psr/psr-4/ [di]: api/phalcon_di.md [di-factorydefault]: api/phalcon_di.md#di-factorydefault [bootstrap]: https://getbootstrap.com/ [devtools]: devtools.md [tutorial-vokuro]: tutorial-vokuro.md [db-models]: db-models.md [installation]: installation.md [webserver-setup]: webserver-setup.md [autoload]: autoload.md [di]: di.md [application]: application.md [controllers]: controllers.md [views]: views.md [html-tagfactory]: html-tagfactory.md [styling]: #styling