Double Negative

Software, code and things.

My take on Model View Controller (MVC)

Model View Controller (MVC) is a very well known design pattern. It is utilised within application development across multiple platforms.

The issue that I have always had with it is not clearly defined - the pattern lacks clarity. What I mean by this is that because people define each piece differently, and because different platforms are constrained in different ways there is no strict definition of what the pattern is.

I spend a lot of my time working in Swift, Java (Android), and PHP. These are all fundamentally different languages.

I work with a pattern (that is heavily based on MVC) which I use for my development across all three languages. It is universal and consistent and can be defined.

This post seeks to outline this pattern with examples. My thoughts are that if you can see the reasoning behind the pattern decisions you can adapt and utilize them as you please without having to work to a questionable strict definition.

At the end of the day, design patterns are tried and tested methodologies for common problems. They allow you to avoid reinventing the wheel. That said, they are not a one fits all kind of thing and you should adapt and develop your applications as needed.

Why do people use MVC

MVC is so popular for a number of reasons.

It allows a separation of concerns.

How the software appears to the user is completely independent of the logic happening behind the scenes.

In principle a user interface can be built by someone without knowledge of the technologies powering the back end logic of the application.

For example:

  • In a web app a designer only needs basic knowledge of HTML to develop an interface.

  • In iOS development, one can simply utilize interface builder.

  • In Android Development, one can utilize the Android studio GUI or simply build an interface with XML.

Interface testing is hard

Interface testing is often achieved through manual means, or through more involved automated means.

For example we utilize Phantom Mochachino to test our web application interfaces.

iOS and Android offer tools to do interface testing, but for complex interfaces they are arduous to work with and are tough to develop and maintain.

MVC allows you test the logic of your application independetnly of your interface. By seperating the various parts of your application you can easily test them using patterns such as Dependency Injection.

It is more maintainable

  • Photos can now have a caption. Model.
  • Lets display that caption on screen. View.
  • Handling page numbers (GET). Controller.

With MVC everything is intuitively positioned in your codebase. You know where to look when you want to do a specific thing. Because your classes and methods have specific responsibilites the code contained within should be clean, concise, and easy to follow.

How I separate my concerns

Views

A view is an output.. a display.. a visual representation of information from my application.

Swift
A UIView subclass. Defined methods allow manipulation of the views on screen.

Java
A class which controls visual representation that may be defined within an xml layout file.

PHP
A static html file, a phtml file, or a template .volt file (I do a lot of work with the Phalcon framework).

Controllers

A controller works with and controls inputs, organizes their processing, and delegates display to a view.

I would describe a controller as controlling the handling of inputs and outputs.

Services

Services do stuff. If i want to get all usernames containing a certain string then a service organizes the execution of the required data gathering operations, processes the data, and returns a response.

The service are the main workhorse of the app.

A service could:

  • log a user into facebook
  • load all of a users uploads from a database
  • write random words to a text file

etc etc

I would describe a service as a controller of operations.

Data access objects

Data access objects control the access and manipulation of data sources.

Regardless of whether your data is stored in a database, a text file, an encoded image etc.. it is a DAO instance that will be used to manipulate the data source.

Models

A model represents a thing. A post, a photo, a review - these are all represented by a model. The model defines the properties of the object that it represents.

In Swift, Java, and PHP a model is simply represented by a class with properties.

View models

A view model models my data in a way that I am happy for it to be utilized within my views.

As mentioned above.. in principle a designer with basic HTML knowledge could develop an interface for my application.

I may want to allow them to utilize data from my model (passed through my controller). The problem is that I may not want them to be able to access some properties of my model. I may also simply not want to directly allow access to a model instance (which could for example be part of an ORM and as such expose methods for data manipulation).

The resolution is to encapsulate a model (a 'thing') within a view model which exposes properties and simple helper methods for designers (with limited knowledge) to utilize within their view design.

In addition to this, view models aid in keeping things DRY. For example in one project I have a method which interacts with multiple database tables (and relationships) to produce a complex permalink. I would not want to reproduce this across the application.

An end to end example

To make the implementation of such a pattern patently clear, I will outline an example - an API endpoint for getting a list of users, and the respective clients (iOS and Android) for displaying said data.

On the web

Firstly we have a controller class which receives the request. How this request is received depends on your server setup, and any frameworks you may or may not be using.

In my case i am utilizing Phalcon and have a setup such that a request for http://domain.com/api/users is routed to a particular method of my controller class.

The controller class takes the request variables (page number for example) and passes them to a service. My UserService has a method called getUsersList which takes the page number as an argument.

This service method calls my UserDao (DAO) which interacts with the database to pull my results. These results are returned as a list of User model instances (thanks to Phalcon's ORM).

These results are processed by the service method into an appropriate form. The model instances may for example be converted to an array of UserViewModel view model instances which are then passed back to the controller.

The controller passes this data to a view which is displayed on screen.

In this case because this is an API endpoint, the view simply outputs the data as JSON.

iOS and Android

Within my applications (the consumers of the endpoint) I once again have a controller class. This class is connected to a view class which displays the interfaces that I have designed in interface builder/xml respectively.

At the appropriate points in the lifecycle of the respective system frameworks, my controller calls a method on a service class APIService. This method contains the networking logic which sends a request to my API endpoint to get the user data.

*Were I interacting with a local data source (for example a SQLite database) I would call an appropriate dao to interact with the database and load the appropriate data.

When this data is returned it is processed and an appropriate response is sent to the controller.

The controller then informs the view about the loaded data, and it is then displayed on screen.

* With our iOS and Android development we do not use view models. This is because behind the scenes, the frameworks of the respective platforms control the application lifecycle and view display. The platforms do not offer an appropriate use case for utilization of view models of the form outlined above.

Conclusion

The beauty of a pattern like that described above is that it is highly malleable. You do not need to utilize view models. Likewise if you dont interact with a data source (really..?) then you of course do not need DAOs at all (or models for that matter).

The nature of an architectural design pattern is that it is merely a set of principles for the organization of your project based on your requirements and needs.

Hopefully the above provides some further insight and gives you some ideas on how you might go about structuring your next project.

iOS - When to layout your views

Ten months ago I wrote an article about the lifecycle of the UIViewController.

My context for writing that post was various issues that I had encountered whilst developing a product based around tabbed content.

More recently I have been working on a project where I have encountered issues associated with laying out views within embedded scroll views.

This post seeks to fill in the gaps on when and where to add/manipulate your views within any context such that your app can be as visually appealling as possible.

What am I trying to achieve

What I want to do is to have:

  • Three pages of content which a user can swipe (left/right) between.

  • The content of each page can be of variable length, and as such each 'page' needs to be vertically scrollable.

  • Because some of the content on each page is dynamically loaded, I want to be able to overlay a loading screen onto each 'page' whilst the various background tasks are executing.

  • Visually, upon opening the view controller (in a modal), I want the inital page to be displayed with the loading overlay in place.

When to layout your views

I personally (wherever possible) would always recommend laying out your views within a storyboard and adding your autolayout constraints utilizing the intuitive GUI available in XCode. To all extents and purposes interface builder is a What You See Is What You Get (WYSIWYG) editor, so assuming you are not doing anything too complex it is ideal for laying out your product.

Unfortunately autolayout and scroll views work slightly differently within interface builder. If you have not already, I highly recommend reading Apples tech notes on UIScrollView And Autolayout.

The long and the short of it is that you define constraints for the contentView of your scroll view rather than the frame of the scroll view itself. Given this, it is quite apparent as to why working with embedded scroll views might get complicated.

Given this, I chose to place a single UIScrollView within my storyboard. I added no content, and simply bound each side to its respective edge. This scroll view is to act as a container for my page content - it is this scroll view that will allow me to scroll each page left/right.

I chose to then build my page content externally in a freeform Xib. The trick for implementing my paging concept was to place three UIView elements within my Xib each with equal width constraints. One can then simply organize their page content within said views.

Laying out your paged content within an Xib

Programatically adding the content

Whilst the seperation outlined above allows for you to build your views in a clean and efficient manner, at some point you need to actually load the content from the Xib and place it into your container scroll view.

To load a view from a Xib I utilize the following code (which I place within an extension of UIView).

    //Load a nib with a given name
    class func loadFromNibNamed(nibNamed: String, bundle : NSBundle = NSBundle.mainBundle()) -> UIView! {

        return UINib(nibName: nibNamed, bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as? UIView
    }

The lifecycle of a UIViewController is extremely important at this point. A basic overview of the timings of the lifecycle methods (that pertain to views) is as follows:

  • viewDidLoad - the class has loaded but individual elements (subviews) are not available to be manipulated, and constraints have not been fully resolved.

  • viewWillAppear - the view will appear but as of yet it has not been added to the view heirachy.

  • viewDidAppear - the view has been added to the view heirachy. All its constraints have been resolved (and you can see the result on your screen).

None of these places seem particularly appropriate to programatically add my content.

In the first two methods, the view is not in the heirachy - you cannot add a subview to a view that isnt there.

By the time we have gotten to viewDidAppear however.. the view has appeared. As such, adding a subview at this point will neccesarily result in a flicker. No thanks.

What you really want to do is add the content view when the view is laying out all of its subviews i.e at the same time as the container scroll view has its constraints resolved.

UIView and layoutSubviews

The UIView class has a method layoutSubviews. This method is called to do exactly what it says on the tin - layout the subviews of that particular view.

This StackOverflow question outlines when exactly layoutSubviews is called.

When the iOS system is building your view, each subview is 'added'. The system follows the heirachy of subviews downwards adding subviews and calling their layoutSubviews method.

Given this, if you wanted to add a border to a UIView, a simple way to do so would be to create a custom class (that extends UIView) and add the border programatically within an overwritten layoutSubviews definition.

One consideration with this is that any manipulation you do will be executed every time layoutSubviews is called. Because of this one should be careful to only conditionally manipulate the view.

For example, when building a pull to refresh component I made sure to only add the control the first time that layoutSubviews was called (using a simple boolean check).

Some further insight on the need to be efficient can be found by reading this.

One issue with this is that it does require you to create a custom subclass for each view you intend to programatically manipulate. I personally am happy to do this - it fits nicely within the patterns I use within my application designs, and keeps things clear and concise.

Setting a view to use a custom class within interface builder

InitializeProtocol

To make things even clearer I have built and implemented a simple protocol - InitializeProtocol.

The premise is simple - All my custom views extend a base class BaseView (which extends UIView).

Within the layoutSubviews definition of my BaseView I conditionally call the initialize method of my InitializeProtocol if (and only if) the class in question (self) implements InitializeProtocol.

Because the BaseView does not, it is up to you to decide if your subclass should implement the protocol or not.

This is essentially the delegate pattern - you delegate the responsibility of initialization to yourself if and only if the protocol has been implemented by the subclass. This additional abstraction simplifies my initialization further.

  • Create a custom view
  • Extend BaseView
  • Implement InitializeProtocol

I get the result that I want as well as a clean, easy to read, maintainable code base.

Implementing the InitializeProtocol in a custom UIView subclass

Partially solving my problem

Given the above, I can now partially solve my problem.

I can utilize the InitializeProtocol to add my content view from a Xib to the scrollView of my UIViewController (which I set up in interface builder).

To do this, I create a custom subview and implement the InitializeProtocol methods. Within initialize I load my Xib define the appropriate constraints, and add it to my scrollView. Simple.

One thing to note is that the constraints aspect of loading a view from a Xib file can get somewhat complex. In this case for example you need to add a constraint to make the width of the loaded content three times the size of your visible screen area. The equal width constraint you defined on the Xib will result in each 'page' in the Xib then being resolved to have the width of one screen (which is what we want).

The loading screen

At this point all I have left to implement is my 'loading screen' requirements.

I like to keep my codebase organized appropriately. As such the code to 'add'/'display' my loading screen(s) should be within the view class to which it relates. This is the view I have built as a Xib.

As such, I create another custom UIView subclass to represent the Xib and set it as my Xibs custom class within interface builder.

This class could simply (once again) initialize the loading screen from another Xib within an implementation of InitializeProtocol.

In my case however things are a little more complex. I only need to show the loading screen if for example a user is logged in. My design means that discerning if this is the case and general control of what is displayed should occur within my view controller.

That said, if my controller decides that a loading screen is to be displayed I still do not want there to be any visual flickering.

Meet viewDidLayoutSubviews

UIViewControllers have two additional lifecycle methods called viewWillLayoutSubviews and viewDidLayoutSubviews.

The documentation for viewDidLayoutSubviews notes that it is:

"Called to notify the view controller that its view has just laid out its subviews."

The method is potentially called multiple times. The following quotation from the docs implies this:

"When the bounds change for a view controller'€™s view, the view adjusts the positions of its subviews and then the system calls this method."

The important thing of note is that this method is called at the minimum before the view is displayed for the first time.

Combined with this knowledge I utilize stateful enumeration to display my loading screen (as appropriate) within this call.

(I have previously discussed Stateful enumeration in Android - the concepts are simple and easily transferable - it may be of interest..?)

For example within viewDidLoad one could discern if the loading screen actually needs to be shown. Then in viewDidLayoutSubviews you could have a condition that displays the loading screen if:

  • it needs to be shown

  • the current state is CONTROLLER_STATE.INITIAL

Once shown you would then update your state such that if/when viewDidLayoutSubviews is called once again the loading screen is not reshown.

Once again, consideration should be given to what you execute within viewDidLayoutSubviews, and when. It can be called multiple times, and you do not want your code to be inefficient.

Conclusion

This conclusion could also be headed TLDR :)

The answer to the initial question, "When should you layout your views in iOS?", is:

  • In interface builder if possible.
  • Otherwise.. in an implementation of layoutSubviews within a custom subclass of UIView where possible.
  • Or.. in an implementation of viewDidLayoutSubviews within your UIViewController if needed.

Consideration should always be given to the efficiency of the code you place within these methods, and there are a number of tricks for making initialization as simple as possible.

Easy right? ;)

Upgrades and instances with the Ghost blogging platform

The Double Negative blog (you are reading it..) runs on the Ghost blogging platform.

The decision to use Ghost was a simple one.

  • It is made by great developers and has been built well.

  • It is written in javascript (Node.js) and allowed me to learn and play with some technologies that I don't regularly use.

  • It is not Wordpress.

  • It is so simple and easy to use - you just write.

I did however recently encounter a few small issues. Nothing significant. Nothing too difficult. Just some small issues that you may encounter when trying to upgrade your self hosted verion of Ghost and/or if you want to run multiple instances of Ghost on the same host.

Upgrading

Ghost provide a How to upgrade guide. It is pretty simple to follow, and explains exactly how to upgrade your Ghost install.

If I recall correctly (I have not touched Wordpress in five years or so), Wordpress has one click upgrades. Unfortunately Ghost does not offer this functionality.. and its propbably for the best.

Firstly.. actually back up your data. I am often 'told' by colleagues/upgrade processes/cats to backup my data, and I rarely listen. In this case however you should absolutely do it. Given that Ghost is powered by SQLite, your data (posts) are held in a single file which it is oh so easy to accidentally delete.

Given that Ghost provides one click backup functionality, you'd be a fool not to.

Now.. you are probably using Forever or Supervisord to manage your Ghost process. One click upgrades with Ghost would more than likely cause more headaches than they would cure as a result of this. Imagine if you upgraded your Ghost install, and the process incorrectly restarted the mechanisms that keep your blog up and running.. crys

I personally use Forever, and one thing I didn't appreciate (it is obvious in hindsight) is that processes are per user. That is to say, my forever process was originally running as user user1 and all of my ghost files were owned by user1. When I restarted the process I was running as root and as a result whilst I could load the blog, I could not login to the control panel.

I was a little bemused, but managed to debug the issue utilizing the Chrome developer tools. A quick look at the network requests being made indicated that the Ajax request processing the login was returning a failed response pertaining to my SQLite database file being read only.

This is one area where Ghost lacks a little mainstream polish - if you were not a developer you'd never be able to debug an issue like this simply because there was no error handling of any sort.. I just could not get past the login screen.

Fortunately, for that situation Ghost offers their hosted solutions which might be of interest if you are not from a technical background.

Multiple instances

Having upgraded this blog, I also wanted to setup another blog for a different website.

If you are trying to do this yourself, Ghost provides a great installation guide. In fact, all their documentation is great.. and there are a lot of tutorials etc from the community too.

The only divergence for multiple blogs is that you need to proxy your HTTP requests to each site (domain) to the respective node instance.

I utilize nginx, and to do this you need to simply direct the request to a particular port as so: proxy_pass http://localhost:1234.

For each blog you need to utilize a different port.

Then all you need to do is specify the matching port in your Ghost config.js for the respective blog.

Simple.

As alluded to above, I utilize different users/owners for each of my Ghost blogs. With the appropriate permissions you get the additional security that someone wont accidentally delete your data or stop you node server. You just need to remember that you have done that when it comes to upgrading ;)

Theming

One of the awesome things about Ghost is its theming.

A lot of our products have extremely complex automated build, testing, and release processes. Of course a blog based on well maintained open source software will unlikely need any such processes.. I only mention this to emphasize the simplicity of Ghost.

All you need to modify is your theme files. Once you have set up your Ghost blog, the only thing you need to change is its visual appearance. Everything else can be done from the control panel.

As such on my development machine I have a singular instance of Ghost running and I build, play, and test my theming for all (two) of my blogs using it. I then push up the themes to the respective blogs and I am done.

This simplicity makes me smile.

One slight annoyance is that you do need to restart your Ghost instance for theme changes to go live and as such you do need a 'release process' of sorts (albeit a very simple one :P )

Conclusion

Use Ghost.

If you like complexity and security issues go ahead and use Wordpress.

But really.. use Ghost. It is so simple and easy to use, has a great community, and.. well.. this post outlines the only 'problems' I have encountered with it, and they really are not very significant :)

FastCGI in 5 minutes

FastCGI "is a binary protocol for interfacing interactive programs with a web server" (from Wikipedia).

In the same vain as my nginx in 15 minutes post, I thought i'd outline FastCGI, and its implementation on nginx with PHPFPM.

A FastCGI server is independent of your web server. You delegate your request to it, it processes it, and returns a response.

FastCGI is a protocol. An implementation of said protocol can be written in any language. PHPFPM is a process manager that implements the FastCGI protocol with a number of optimizations. It is now part of the PHP core and is well used on the web.

Whereas previous incarnations of CGI created a new request per process the FastCGI protocol processes multiple requests within the same process (multiplexing). This allows for concurrency and handling of higher loads.

The FastCGI protocol seeks to resolves many similar issues in the CGI protocol that nginx seeks to resolve in earlier versions of Apache.

nginx

nginx integrates with the FastCGI protocol throught its fastcgi module. That is to say it knows how to interface with a FastCGI server that implements the FastCGI protocol. This makes connecting to a FastCGI server extremely simple.

Communication occurs via interprocess communication (IPC). For a simple setup you can connect to a unix socket. For a more complex setup you might want to communicate with multiple servers using TCP sockets.

The most important fastcgi_param is SCRIPT_FILENAME which indicates as to where on the filesystem a file should be loaded for a particular request.

I choose to define my server root as follows:

set $root_path '/path/to/files';  
root $root_path;  

I then utilize the $root variable within my location blocks for static image files as well as my location block for passing php files to my FastCGI server.

Within the latter block I use:

fastcgi_param SCRIPT_FILENAME $root_path$fastcgi_script_name;

This maps a request for myfile.php to /path/to/files/myfile.php

You can utilize the fastcgi_split_path_info directive to allow for customized URL structures.

As long as you specify a regular expression with two capturing blocks you could direct a request to http://domain.com/request/my_file/hash to /path/to/files/myfile.php with relative ease.

You are only limited by your knowledge of regular expressions :)

Another interesting tidbit regarding the nginx integration is fastcgi_intercept_errors on.

This directive allows for a response from the FastCGI server to be directed to the appropriate location block based on your defined error_page directive.

Through this directive it is easy to display a custom 404 page for example should FastCGI return an error response.

PHPFPM

PHPFPM is a "process manager to manage the FastCGI SAPI (Server API) in PHP" (source).

In essence, what that means is that PHPFPM manages the creation of PHP processes (as required) to process the requests sent to it by the webserver.

It implements the FastCGI protocol such that for example, data sent to it as a fastcgi_param (when using nginx) can be processed and utilized appropriately.

When running PHPFPM on a local machine (server) it 'runs' the server to which one directs their PHP requests.

For usage with nginx you would connect to the server through a unix socket using the fastcgi_pass directive (as outlined above).

fastcgi_pass unix:/var/run/php5-fpm.sock;  

Summary

nginx, PHP, and FastCGI are a power combination in web application development because they integrate so seemlessly together with one another.

Configuration is simple, and they allow for deployment of dynamic websites that can scale with ease.