Server side Swift for Laravel developers part 1

2017-07-18

tl;dr

Server side Swift is super snappy, the performance is incredible, and the memory footprint is tiny.

Vapor 2 was a delightful surprise that it feels very Laravel-ish regarding structure.

Swift in its nature of being strictly type hinted (and the Internet is very ”stringy”) makes some operations like models to have a lot of boiler plate. Vapor tries to overcome this with its Node package.

Download complete Xcode project for this example

Intro

After doing all my web development in PHP since version 4.1 (the dark ages), I almost gave up a few years ago and decided to learn Ruby and Ruby on Rails. By accident, I discovered Laravel and have been using it since. I have also been programming mobile apps in Swift and Objective-C for Apple's platforms and released my first app on iTunes Store in 2010.

The developers of Vapor credits Laravel as an excellent framework, and early on, it was an inspiration for them when writing a server side web framework for Swift. I did decide to give it a try.

The inspiration from Laravel shows very well when you start digging into Vapor. So, If you're a Laravel/PHP user, Vapor should look familiar to get you started. Swift in it self is influenced by functional programming, so you will get a lot of the collection functionality you find in Laravel straight out of the box. Regarding features, I would say Vapor 2 sits somewhere between Lumen and Laravel. I think it’s always an excellent idea to learn more languages to understand the bigger picture.

Vapor is already one of the most used web frameworks for Swift, and the HTTP server and WebSocket are also written in pure Swift. That may give the framework a slight performance penalty compared to others that are using low-level APIs, on the other side it's not dependent on compiled 3rd party libraries which make Vapor easier to use. Rumors tell that Apple is starting to use this framework internally.

The language Swift it self is designed to be deployed on small devices with restricted resources. Therefore running Swift on a server is very efficient with a low memory footprint. That is interesting because if you run applications in a cloud, most clouds charge you by memory usage.

We all know the controversies of benchmarks, and it’s not the whole picture. Swift is a compiled language and PHP is a scripting language. You cannot compare these straight off. Anyway, I decided to build a simple CRUD-app with Vapor 2 and Swift and see how it ”feels” instead.


Install Xcode, Homebrew Tap and Vapor

Follow the instructions on Vapor’s site Install: macOS - Vapor Docs

Important, make sure that you have launched Xcode at least once otherwise some needed components are not installed. Also, check Xcode > Preferences > Locations > Command Line Tools that the tools are installed.

After you have installed Vapor, we will continue to install the necessary drivers for MySQL.


Create a new project

Should not be to unfamiliar if you are used to Laravel Artisan

vapor new RadioAPI --template=web

cd RadioAPI

Generate a Xcode project by entering.

vapor xcode

Generating Xcode project After the generation is done, press y to open the Xcode project.

Select right scheme and press the play-button to the left.

Run

Visit http://localhost:8080 and you should see that it works.


Install C MySQL library

Since you are a Laravel developer, I assume you are using Laravel Valet and have MySQL installed via Homebrew. Otherwise, install MySQL with homebrew.

brew install mysql

If you are using MAMP, you have to quit MAMP's MySQL-server first. You cannot have both MySQL running on the same ports.

To use MySQL in Vapor, you need to have the C MySQL library installed on your computer.

brew install vapor/tap/cmysql


Install and configure MySQL-drivers

Next, we are going to configure the MySQL-connection. Since I am used to MySQL, and it’s officially supported I am going to stick with MySQL in this example.

Open Package.swift and add this dependency:

.Package(url: "https://github.com/vapor/mysql-provider.git", majorVersion: 2)

Add package

Save and update the Swift packages with this command in the terminal (just like composer update in PHP):

swift build

And rebuild the Xcode project to Xcode can resolve the new modules

vapor xcode

Create a MySQL-database with your preferred tool. I use Sequel Pro.

Create a database

Create mysql.json and save inside Config/ in your Vapor-project. Add your connection settings

{
    "hostname": "127.0.0.1",
    "user": "root",
    "password": "",
    "database": "vapor"
}

Since we like Laravel Eloquent so much we are going to go for Vapor’s equivalent – Fluent. Add MySQL as the driver in Config/fluent.json

{
    "driver": "mysql"
}

Test your setup

Replace Sources/Run/main.swift with this

import App
import MySQLProvider

let config = try Config()
try config.addProvider(MySQLProvider.Provider.self)
try config.setup()

let drop = try Droplet(config)
try drop.setup()

drop.get("version") { request in 
   let db = try drop.mysql()
    let version = try db.raw("SELECT version()")
    return JSON(node: version)
}

try drop.run()

A droplet in Vapor is equivalent to Laravel’s concept of the service container. In advanced setups, you can even have several droplets. Just to make sure it all works we add this directly here, but we will delete this later on.

Hit click the Run-button in Xcode to compile your changes

Run in Xcode



Open your web browser and visit* http://localhost:8080/version

MySQL response


What language is F-Bar written in?

2017-05-03

Every once in a while I get questions about which languages I used to author F-Bar and GitFTP-Deploy.

I wrote F-Bar in 100% Swift 3 and GitFTP-Deploy has a mix of Objective-C and Swift. The reason is that Swift was not mature when it started writing the first classes of GitFTP-Deploy.

There are other techniques to write mobile and desktop apps today. Electron is one of the more popular. To be honest, I have not written any major apps in Electron or any other hybrid frameworks.

The objective is compelling to be able to write a fully cross-platform app that shares codebase and can run on macOS, Windows, and Linux. However, in my research before starting my projects, there are several significant downsides with Electron.

Memory usage

An Electron app is essentially a fully-featured Chromium browser and a Node.js process that communicate via IPC. The is, unfortunately, a show stopper for a small and long-time running menubar-app. GitFTP-Deploy is shuffling around thousands of files with tiny memory footprint.

Large builds

Packaged Electron apps contain everything they need to run, so they're typically quite large. The “Hello World” app for Electron weighs 115 MB. This overhead is not really a problem for large apps like Visual Studio Code. It does pose a problem for smaller apps that would like to use the Electron model. A typical desktop user may have a dozen utilities open. If each of these has a copy of the whole Electron stack in memory, it wastes over a gigabyte for essentially nothing.

Not truly native

The super snappy hierarchal menus native in macOS is not available in a cross-platform environment.

By all means, I don’t want do dismiss Electron, it’s an amazing project, but it’s still important to choose the right tool for a particular job. I may case if think that going native and Swift gives me more control and F-Bar is a lot less conservative with the memory.


F-Bar 1.2 released. Better monitoring

2017-04-12

The #2 most requested feature is here: the ability to disable monitoring for individual sites. Like this, you can turn off for the site with the name ”default” or if the site is behind a basic auth.

Click "Preferences…"

Bild

Click ”More Settings…”

More settings

Check the checkbox, done. Profit! :-)

More settings

Another typical scenario is that the name of the site, defined in Laravel Forge, is not the same as the public URL. Forge is still managing the site as usual, but you would like to monitor the site. With URL Alias you can do this with ease.

Bild

Nice to have features

Fixed so that you can save configurations without closing configuration dialog. Faster workflow, if you want to test back and forth.

Also, I added a warning if you try to close the dialog with unsaved changes.

I have been overwhelmed by all your good feedback and reports, if you have any, please don’t hesitate to drop me an email

Bugfixes

  • Crash in add API-keys dialog is fixed
  • Fixed a memory leak

F-Bar product page


Troubleshoot Nginx, the first step

2017-04-06

Suddenly Nginx won't start. Where to I begin to troubleshoot. First, check the configuration file for Nginx.

sudo nginx -t

Aha, a misplaced character a line 52

Error screen

Using Laravel Forge and F-Bar together it's easy to find the error around line 52, a misplaced }

F-Bar

Done!

Profit!


F-Bar 1.1 - multi-account support

2017-04-03

New features

  • Multi-account support! Add as how many you want, and re-order them as you like.
  • Line-numbering for configuration windows and log viewers.
  • Direct link to Laravel Forge from each site.
  • Better validation when entering an API-key. Trimming of white spaces at the end.

Bugfixes

  • Resizing of configuration and log viewer window work as expected
  • Fixed memory leaks
  • A 20-second delay before monitoring starts if enabled. Let’s the computer connect to Wifi.
  • Bigger fonts
  • Turned off spell check on configuration windows

What's next?

Since multi-account has been the number one request, I have prioritized this one. Next up is the ability to

  • Exclude some sites from monitoring
  • Put an ”alias” of a site. The site ”name” that the Forge API provides may not be the actual domain used externally.
  • ”Alias” of a server. If you are connecting to servers from an internal IP.

Download


Subscribe to blog updates