The problem is still, how would I call the controller method? I still can't
instantiate a new instance of the controller and call a given method on the
instance.
I was able to partially get this working, but I realized that I still can't
instantiate a new controller on each request. I can't figure out a good way
to store the class method
*Matthew Davies*
Junior Developer, GeoStrategies <http://geostrategies.com>
Director of Photography, OffBlock Films <http://offblockfilms.com>
209-225-3246 <209-225.3246> | 209-202-3284 | daviesgeek@gmail.com |
daviesgeek.com
<Facebook; <http://us.linkedin.com/in/daviesgeek>
<http://twitter.com/daviesgeek> <Page not found;
<http://github.com/daviesgeek>
···
On Fri, Dec 11, 2015 at 8:14 AM, Jeremy Pereira < jeremy.j.pereira@googlemail.com> wrote:
> On 10 Dec 2015, at 20:22, Matthew Davies via swift-users < > swift-users@swift.org> wrote:
>
> I'm building a URL router in which I'd like to pass a controller and a
method. I don't want to instantiate all the controllers up front and pass
the methods in as closures, nor do I want old controller instances still
kept around. If there's a better way, I'm definitely open to any
suggestions. I'm still learning the "Swift" way to do things.The way I would do this is to define my controller interface with a
protocol and then have a dictionary of the following type:[String: (Request) throws -> Controller]
where Controller is the protocol and Request is the HTTP request.
So you have a dictionary of URLs to functions (or closures) that create
instances that conform to the Controller protocol. The closure takes a
parameter of the HTTP request so it has the option of choosing the returned
instance based on the method or headers or parameters in the request.In my implementation, I took the path part of the URL and if it was in the
dictionary it would use the returned closure to create the controller. If
it wasn’t there, I chopped off the last path part and tried again and so on
until I was left with “/“ which always maps to a controller.The closure is allowed to throw so I could put something like this in for
a path{ _ in throw HTTPError(404) }
which would be handled further up the call chain by generating a 404
response.