Replace controller's .Register with .Handle and AddDependencies with .Register in order to be aligned with the 'hero' package, all examples and docs are updated, it's crazy how I can't stop even on Christmas

Former-commit-id: 3b42963e9806e327ee42942cf156bda6059eaf8f
This commit is contained in:
Gerasimos (Makis) Maropoulos 2017-12-27 04:15:41 +02:00
parent 8fd4dc2b4b
commit b282e7c563
25 changed files with 110 additions and 119 deletions

View File

@ -22,7 +22,7 @@ func main() {
app.StaticWeb("/public", publicDir) app.StaticWeb("/public", publicDir)
app.OnAnyErrorCode(onError) app.OnAnyErrorCode(onError)
mvc.New(app).Register(new(controllers.HomeController)) mvc.New(app).Handle(new(controllers.HomeController))
app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker) app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker)
} }

View File

@ -14,7 +14,7 @@ import (
func main() { func main() {
app := iris.New() app := iris.New()
mvc.New(app.Party("/api/values/{id}")). mvc.New(app.Party("/api/values/{id}")).
Register(new(controllers.ValuesController)) Handle(new(controllers.ValuesController))
app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker) app.Run(iris.Addr(":5000"), iris.WithoutVersionChecker)
} }

View File

@ -127,8 +127,7 @@ All HTTP Methods are supported, for example if want to serve `GET`
then the controller should have a function named `Get()`, then the controller should have a function named `Get()`,
you can define more than one method function to serve in the same Controller. you can define more than one method function to serve in the same Controller.
Register custom controller's struct's methods as handlers with custom paths(even with regex parametermized path) Serve custom controller's struct's methods as handlers with custom paths(even with regex parametermized path) via the `BeforeActivation` custom event callback, per-controller. Example:
via the `BeforeActivation` custom event callback, per-controller. Example:
```go ```go
import ( import (
@ -143,9 +142,9 @@ func main() {
} }
func myMVC(app *mvc.Application) { func myMVC(app *mvc.Application) {
// app.AddDependencies(...) // app.Register(...)
// app.Router.Use/UseGlobal/Done(...) // app.Router.Use/UseGlobal/Done(...)
app.Register(new(MyController)) app.Handle(new(MyController))
} }
type MyController struct {} type MyController struct {}
@ -192,13 +191,13 @@ Optional `EndRequest(ctx)` function to perform any finalization after any method
Inheritance, recursively, see for example our `mvc.SessionController`, it has the `Session *sessions.Session` and `Manager *sessions.Sessions` as embedded fields Inheritance, recursively, see for example our `mvc.SessionController`, it has the `Session *sessions.Session` and `Manager *sessions.Sessions` as embedded fields
which are filled by its `BeginRequest`, [here](https://github.com/kataras/iris/blob/master/mvc/session_controller.go). which are filled by its `BeginRequest`, [here](https://github.com/kataras/iris/blob/master/mvc/session_controller.go).
This is just an example, you could use the `sessions.Session` which returned from the manager's `Start` as a dynamic dependency to the MVC Application, i.e This is just an example, you could use the `sessions.Session` which returned from the manager's `Start` as a dynamic dependency to the MVC Application, i.e
`mvcApp.AddDependencies(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)`. `mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)`.
Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed. Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed.
When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods
with the `By` word, uppercase is a new sub path. Example: with the `By` word, uppercase is a new sub path. Example:
If `mvc.New(app.Party("/user")).Register(new(user.Controller))` If `mvc.New(app.Party("/user")).Handle(new(user.Controller))`
- `func(*Controller) Get()` - `GET:/user`. - `func(*Controller) Get()` - `GET:/user`.
- `func(*Controller) Post()` - `POST:/user`. - `func(*Controller) Post()` - `POST:/user`.
@ -209,11 +208,11 @@ If `mvc.New(app.Party("/user")).Register(new(user.Controller))`
- `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}` - `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}`
- `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}` - `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}`
If `mvc.New(app.Party("/profile")).Register(new(profile.Controller))` If `mvc.New(app.Party("/profile")).Handle(new(profile.Controller))`
- `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}` - `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}`
If `mvc.New(app.Party("/assets")).Register(new(file.Controller))` If `mvc.New(app.Party("/assets")).Handle(new(file.Controller))`
- `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}` - `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}`

View File

@ -2,7 +2,6 @@ package main
import ( import (
"github.com/kataras/iris" "github.com/kataras/iris"
"github.com/kataras/iris/hero" "github.com/kataras/iris/hero"
) )

View File

@ -26,7 +26,7 @@ func main() {
movieService := services.NewMovieService(repo) movieService := services.NewMovieService(repo)
hero.Register(movieService) hero.Register(movieService)
// Register our routes with hero handlers. // Serve our routes with hero handlers.
app.PartyFunc("/hello", func(r iris.Party) { app.PartyFunc("/hello", func(r iris.Party) {
r.Get("/", hero.Handler(routes.Hello)) r.Get("/", hero.Handler(routes.Hello))
r.Get("/{name}", hero.Handler(routes.HelloName)) r.Get("/{name}", hero.Handler(routes.HelloName))

View File

@ -14,7 +14,7 @@ All HTTP Methods are supported, for example if want to serve `GET`
then the controller should have a function named `Get()`, then the controller should have a function named `Get()`,
you can define more than one method function to serve in the same Controller. you can define more than one method function to serve in the same Controller.
Register custom controller's struct's methods as handlers with custom paths(even with regex parametermized path) Serve custom controller's struct's methods as handlers with custom paths(even with regex parametermized path)
via the `BeforeActivation` custom event callback, per-controller. Example: via the `BeforeActivation` custom event callback, per-controller. Example:
```go ```go
@ -30,9 +30,9 @@ func main() {
} }
func myMVC(app *mvc.Application) { func myMVC(app *mvc.Application) {
// app.AddDependencies(...) // app.Register(...)
// app.Router.Use/UseGlobal/Done(...) // app.Router.Use/UseGlobal/Done(...)
app.Register(new(MyController)) app.Handle(new(MyController))
} }
type MyController struct {} type MyController struct {}
@ -79,13 +79,13 @@ Optional `EndRequest(ctx)` function to perform any finalization after any method
Inheritance, recursively, see for example our `mvc.SessionController`, it has the `Session *sessions.Session` and `Manager *sessions.Sessions` as embedded fields Inheritance, recursively, see for example our `mvc.SessionController`, it has the `Session *sessions.Session` and `Manager *sessions.Sessions` as embedded fields
which are filled by its `BeginRequest`, [here](https://github.com/kataras/iris/blob/master/mvc/session_controller.go). which are filled by its `BeginRequest`, [here](https://github.com/kataras/iris/blob/master/mvc/session_controller.go).
This is just an example, you could use the `sessions.Session` as a dependency to the MVC Application, i.e This is just an example, you could use the `sessions.Session` as a dependency to the MVC Application, i.e
`mvcApp.AddDependencies(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)`. `mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)`.
Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed. Access to the dynamic path parameters via the controller's methods' input arguments, no binding is needed.
When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods When you use the Iris' default syntax to parse handlers from a controller, you need to suffix the methods
with the `By` word, uppercase is a new sub path. Example: with the `By` word, uppercase is a new sub path. Example:
If `mvc.New(app.Party("/user")).Register(new(user.Controller))` If `mvc.New(app.Party("/user")).Handle(new(user.Controller))`
- `func(*Controller) Get()` - `GET:/user`. - `func(*Controller) Get()` - `GET:/user`.
- `func(*Controller) Post()` - `POST:/user`. - `func(*Controller) Post()` - `POST:/user`.
@ -96,11 +96,11 @@ If `mvc.New(app.Party("/user")).Register(new(user.Controller))`
- `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}` - `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}`
- `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}` - `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}`
If `mvc.New(app.Party("/profile")).Register(new(profile.Controller))` If `mvc.New(app.Party("/profile")).Handle(new(profile.Controller))`
- `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}` - `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}`
If `mvc.New(app.Party("/assets")).Register(new(file.Controller))` If `mvc.New(app.Party("/assets")).Handle(new(file.Controller))`
- `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}` - `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}`

View File

@ -38,8 +38,8 @@ func newApp() *iris.Application {
app.Use(recover.New()) app.Use(recover.New())
app.Use(logger.New()) app.Use(logger.New())
// Register a controller based on the root Router, "/". // Serve a controller based on the root Router, "/".
mvc.New(app).Register(new(ExampleController)) mvc.New(app).Handle(new(ExampleController))
return app return app
} }

View File

@ -36,7 +36,7 @@ func main() {
ctx.View("shared/error.html") ctx.View("shared/error.html")
}) })
// ---- Register our controllers. ---- // ---- Serve our controllers. ----
// Prepare our repositories and services. // Prepare our repositories and services.
db, err := datasource.LoadUsers(datasource.Memory) db, err := datasource.LoadUsers(datasource.Memory)
@ -53,8 +53,8 @@ func main() {
// for the /users based requests. // for the /users based requests.
users.Router.Use(middleware.BasicAuth) users.Router.Use(middleware.BasicAuth)
// Bind the "userService" to the UserController's Service (interface) field. // Bind the "userService" to the UserController's Service (interface) field.
users.AddDependencies(userService) users.Register(userService)
users.Register(new(controllers.UsersController)) users.Handle(new(controllers.UsersController))
// "/user" based mvc application. // "/user" based mvc application.
sessManager := sessions.New(sessions.Config{ sessManager := sessions.New(sessions.Config{
@ -62,11 +62,11 @@ func main() {
Expires: 24 * time.Hour, Expires: 24 * time.Hour,
}) })
user := mvc.New(app.Party("/user")) user := mvc.New(app.Party("/user"))
user.AddDependencies( user.Register(
userService, userService,
sessManager.Start, sessManager.Start,
) )
user.Register(new(controllers.UserController)) user.Handle(new(controllers.UserController))
// http://localhost:8080/noexist // http://localhost:8080/noexist
// and all controller's methods like // and all controller's methods like

View File

@ -20,11 +20,11 @@ func main() {
// Load the template files. // Load the template files.
app.RegisterView(iris.HTML("./web/views", ".html")) app.RegisterView(iris.HTML("./web/views", ".html"))
// Register our controllers. // Serve our controllers.
mvc.New(app.Party("/hello")).Register(new(controllers.HelloController)) mvc.New(app.Party("/hello")).Handle(new(controllers.HelloController))
// You can also split the code you write to configure an mvc.Application // You can also split the code you write to configure an mvc.Application
// using the `Configure` method, as shown below. // using the `mvc.Configure` method, as shown below.
mvc.New(app.Party("/movies")).Configure(movies) mvc.Configure(app.Party("/movies"), movies)
// http://localhost:8080/hello // http://localhost:8080/hello
// http://localhost:8080/hello/iris // http://localhost:8080/hello/iris
@ -52,10 +52,11 @@ func movies(app *mvc.Application) {
repo := repositories.NewMovieRepository(datasource.Movies) repo := repositories.NewMovieRepository(datasource.Movies)
// Create our movie service, we will bind it to the movie app's dependencies. // Create our movie service, we will bind it to the movie app's dependencies.
movieService := services.NewMovieService(repo) movieService := services.NewMovieService(repo)
app.AddDependencies(movieService) app.Register(movieService)
// Register our movies controller. // serve our movies controller.
// Note that you can register more than one controller // Note that you can serve more than one controller
// you can alos create child mvc apps using the `movies.NewChild()` if you want. // you can also create child mvc apps using the `movies.Party(relativePath)` or `movies.Clone(app.Party(...))`
app.Register(new(controllers.MovieController)) // if you want.
app.Handle(new(controllers.MovieController))
} }

View File

@ -42,7 +42,7 @@ func newApp() *iris.Application {
visitApp := mvc.New(app.Party("/")) visitApp := mvc.New(app.Party("/"))
// bind the current *session.Session, which is required, to the `VisitController.Session` // bind the current *session.Session, which is required, to the `VisitController.Session`
// and the time.Now() to the `VisitController.StartTime`. // and the time.Now() to the `VisitController.StartTime`.
visitApp.AddDependencies( visitApp.Register(
// if dependency is a function which accepts // if dependency is a function which accepts
// a Context and returns a single value // a Context and returns a single value
// then the result type of this function is resolved by the controller // then the result type of this function is resolved by the controller
@ -55,7 +55,7 @@ func newApp() *iris.Application {
sess.Start, sess.Start,
time.Now(), time.Now(),
) )
visitApp.Register(new(VisitController)) visitApp.Handle(new(VisitController))
return app return app
} }

View File

@ -10,7 +10,7 @@ import (
func main() { func main() {
app := iris.New() app := iris.New()
mvc.New(app.Party("/")).Register(&globalVisitorsController{visits: 0}) mvc.New(app.Party("/")).Handle(&globalVisitorsController{visits: 0})
// http://localhost:8080 // http://localhost:8080
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))

View File

@ -31,9 +31,9 @@ func configureMVC(m *mvc.Application) {
m.Router.Any("/iris-ws.js", websocket.ClientHandler()) m.Router.Any("/iris-ws.js", websocket.ClientHandler())
// This will bind the result of ws.Upgrade which is a websocket.Connection // This will bind the result of ws.Upgrade which is a websocket.Connection
// to the controller(s) registered via `m.Register`. // to the controller(s) served by the `m.Handle`.
m.AddDependencies(ws.Upgrade) m.Register(ws.Upgrade)
m.Register(new(websocketController)) m.Handle(new(websocketController))
} }
var visits uint64 var visits uint64

View File

@ -36,12 +36,12 @@ func configureMVC(app *mvc.Application) {
Expires: 24 * time.Hour, Expires: 24 * time.Hour,
}) })
userApp := app.NewChild(app.Router.Party("/user")) userApp := app.Party("/user")
userApp.AddDependencies( userApp.Register(
user.NewDataSource(), user.NewDataSource(),
manager.Start, manager.Start,
) )
userApp.Register(new(user.Controller)) userApp.Handle(new(user.Controller))
} }
func configure(app *iris.Application) { func configure(app *iris.Application) {

View File

@ -11,7 +11,7 @@ func main() {
templates := iris.HTML("./views", ".html").Layout("shared/layout.html") templates := iris.HTML("./views", ".html").Layout("shared/layout.html")
app.RegisterView(templates) app.RegisterView(templates)
mvc.New(app).Register(new(Controller)) mvc.New(app).Handle(new(Controller))
// http://localhost:9091 // http://localhost:9091
app.Run(iris.Addr(":9091")) app.Run(iris.Addr(":9091"))

View File

@ -10,10 +10,10 @@ type postValue func(string) string
func main() { func main() {
app := iris.New() app := iris.New()
mvc.New(app.Party("/user")).AddDependencies( mvc.New(app.Party("/user")).Register(
func(ctx iris.Context) postValue { func(ctx iris.Context) postValue {
return ctx.PostValue return ctx.PostValue
}).Register(new(UserController)) }).Handle(new(UserController))
// GET http://localhost:9092/user // GET http://localhost:9092/user
// GET http://localhost:9092/user/42 // GET http://localhost:9092/user/42

View File

@ -41,14 +41,14 @@ func main() {
todosApp := mvc.New(todosRouter) todosApp := mvc.New(todosRouter)
// any dependencies bindings here... // any dependencies bindings here...
todosApp.AddDependencies( todosApp.Register(
todo.NewMemoryService(), todo.NewMemoryService(),
sess.Start, sess.Start,
ws.Upgrade, ws.Upgrade,
) )
// controllers registration here... // controllers registration here...
todosApp.Register(new(controllers.TodoController)) todosApp.Handle(new(controllers.TodoController))
// start the web server at http://localhost:8080 // start the web server at http://localhost:8080
app.Run(iris.Addr(":8080"), iris.WithoutVersionChecker) app.Run(iris.Addr(":8080"), iris.WithoutVersionChecker)

View File

@ -31,18 +31,18 @@ func (app *Application) Controller(relPath string, c interface{}, _ ...interface
// ... // ...
) )
// or use it like this: ).AddDependencies(...).Register(new(%s)) // or use it like this: ).Register(...).Handle(new(%s))
mvc.Configure(app.Party("%s"), myMVC) mvc.Configure(app.Party("%s"), myMVC)
func myMVC(mvcApp *mvc.Application) { func myMVC(mvcApp *mvc.Application) {
mvcApp.AddDependencies( mvcApp.Register(
Struct_Values_Dependencies_Binded_To_The_Fields_Or_And_To_Methods, Struct_Values_Dependencies_Binded_To_The_Fields_Or_And_To_Methods,
Or_And_Func_Values_Dependencies_Binded_To_The_Fields_Or_And_To_Methods, Or_And_Func_Values_Dependencies_Binded_To_The_Fields_Or_And_To_Methods,
) )
mvcApp.Router.Use(Any_Middleware) mvcApp.Router.Use(Any_Middleware)
mvcApp.Register(new(%s)) mvcApp.Handle(new(%s))
} }
The new MVC implementation contains a lot more than the above, The new MVC implementation contains a lot more than the above,

18
doc.go
View File

@ -1504,8 +1504,8 @@ Example Code:
app.Use(recover.New()) app.Use(recover.New())
app.Use(logger.New()) app.Use(logger.New())
// Register a controller based on the root Router, "/". // Serve a controller based on the root Router, "/".
mvc.New(app).Register(new(ExampleController)) mvc.New(app).Handle(new(ExampleController))
// http://localhost:8080 // http://localhost:8080
// http://localhost:8080/ping // http://localhost:8080/ping
@ -1613,9 +1613,9 @@ via the `BeforeActivation` custom event callback, per-controller. Example:
} }
func myMVC(app *mvc.Application) { func myMVC(app *mvc.Application) {
// app.AddDependencies(...) // app.Register(...)
// app.Router.Use/UseGlobal/Done(...) // app.Router.Use/UseGlobal/Done(...)
app.Register(new(MyController)) app.Handle(new(MyController))
} }
type MyController struct {} type MyController struct {}
@ -1665,7 +1665,7 @@ Optional `EndRequest(ctx)` function to perform any finalization after any method
Session dynamic dependency via manager's `Start` to the MVC Application, i.e Session dynamic dependency via manager's `Start` to the MVC Application, i.e
mvcApp.AddDependencies(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start) mvcApp.Register(sessions.New(sessions.Config{Cookie: "iris_session_id"}).Start)
Inheritance, recursively. Inheritance, recursively.
@ -1675,7 +1675,7 @@ with the `By` word, uppercase is a new sub path. Example:
Register one or more relative paths and able to get path parameters, i.e Register one or more relative paths and able to get path parameters, i.e
If `mvc.New(app.Party("/user")).Register(new(user.Controller))` If `mvc.New(app.Party("/user")).Handle(new(user.Controller))`
- `func(*Controller) Get()` - `GET:/user` , as usual. - `func(*Controller) Get()` - `GET:/user` , as usual.
- `func(*Controller) Post()` - `POST:/user`, as usual. - `func(*Controller) Post()` - `POST:/user`, as usual.
@ -1686,15 +1686,15 @@ Register one or more relative paths and able to get path parameters, i.e
- `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}` - `func(*Controller) GetBy(id int64)` - `GET:/user/{param:long}`
- `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}` - `func(*Controller) PostBy(id int64)` - `POST:/user/{param:long}`
If `mvc.New(app.Party("/profile")).Register(new(profile.Controller))` If `mvc.New(app.Party("/profile")).Handle(new(profile.Controller))`
- `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}` - `func(*Controller) GetBy(username string)` - `GET:/profile/{param:string}`
If `mvc.New(app.Party("/assets")).Register(new(file.Controller))` If `mvc.New(app.Party("/assets")).Handle(new(file.Controller))`
- `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}` - `func(*Controller) GetByWildard(path string)` - `GET:/assets/{param:path}`
If `mvc.New(app.Party("/equality")).Register(new(profile.Equality))` If `mvc.New(app.Party("/equality")).Handle(new(profile.Equality))`
- `func(*Controller) GetBy(is bool)` - `GET:/equality/{param:boolean}` - `func(*Controller) GetBy(is bool)` - `GET:/equality/{param:boolean}`
- `func(*Controller) GetByOtherBy(is bool, otherID int64)` - `GET:/equality/{paramfirst:boolean}/other/{paramsecond:long}` - `func(*Controller) GetByOtherBy(is bool, otherID int64)` - `GET:/equality/{paramfirst:boolean}/other/{paramsecond:long}`

View File

@ -1,11 +0,0 @@
I can do one of the followings to this "di" folder when I finish the cleanup and document it a bit,
although I'm sick I will try to finish it tomorrow.
End-users don't need this.
1) So, rename this to "internal".
I don't know if something similar exist in Go,
it's a dependency injection framework at the end, and a very fast one.
2) So I'm thinking to push it to a different repo,
like https://github.com/kataras/di or even to my small common https://github.com/kataras/pkg collection.

View File

@ -71,8 +71,8 @@ func TestControllerHandle(t *testing.T) {
app := iris.New() app := iris.New()
m := New(app) m := New(app)
m.AddDependencies(&TestServiceImpl{prefix: "service:"}) m.Register(&TestServiceImpl{prefix: "service:"})
m.Register(new(testControllerHandle)) m.Handle(new(testControllerHandle))
e := httptest.New(t, app) e := httptest.New(t, app)

View File

@ -69,7 +69,7 @@ func (c *testControllerMethodResult) GetThingWithTryDefaultBy(index int) Result
func TestControllerMethodResult(t *testing.T) { func TestControllerMethodResult(t *testing.T) {
app := iris.New() app := iris.New()
New(app).Register(new(testControllerMethodResult)) New(app).Handle(new(testControllerMethodResult))
e := httptest.New(t, app) e := httptest.New(t, app)
@ -173,7 +173,7 @@ func (c *testControllerMethodResultTypes) GetCustomStructWithError() (s testCust
func TestControllerMethodResultTypes(t *testing.T) { func TestControllerMethodResultTypes(t *testing.T) {
app := iris.New() app := iris.New()
New(app).Register(new(testControllerMethodResultTypes)) New(app).Handle(new(testControllerMethodResultTypes))
e := httptest.New(t, app) e := httptest.New(t, app)
@ -262,8 +262,8 @@ func (t *testControllerViewResultRespectCtxViewData) Get() Result {
func TestControllerViewResultRespectCtxViewData(t *testing.T) { func TestControllerViewResultRespectCtxViewData(t *testing.T) {
app := iris.New() app := iris.New()
m := New(app.Party("/")) m := New(app.Party("/"))
m.AddDependencies(t) m.Register(t)
m.Register(new(testControllerViewResultRespectCtxViewData)) m.Handle(new(testControllerViewResultRespectCtxViewData))
e := httptest.New(t, app) e := httptest.New(t, app)

View File

@ -64,9 +64,9 @@ func (c *testControllerAny) Any() {
func TestControllerMethodFuncs(t *testing.T) { func TestControllerMethodFuncs(t *testing.T) {
app := iris.New() app := iris.New()
New(app).Register(new(testController)) New(app).Handle(new(testController))
New(app.Party("/all")).Register(new(testControllerAll)) New(app.Party("/all")).Handle(new(testControllerAll))
New(app.Party("/any")).Register(new(testControllerAny)) New(app.Party("/any")).Handle(new(testControllerAny))
e := httptest.New(t, app) e := httptest.New(t, app)
for _, method := range router.AllMethods { for _, method := range router.AllMethods {
@ -112,7 +112,7 @@ func (c *testControllerBeginAndEndRequestFunc) Post() {
func TestControllerBeginAndEndRequestFunc(t *testing.T) { func TestControllerBeginAndEndRequestFunc(t *testing.T) {
app := iris.New() app := iris.New()
New(app.Party("/profile/{username}")). New(app.Party("/profile/{username}")).
Register(new(testControllerBeginAndEndRequestFunc)) Handle(new(testControllerBeginAndEndRequestFunc))
e := httptest.New(t, app) e := httptest.New(t, app)
usernames := []string{ usernames := []string{
@ -157,7 +157,7 @@ func TestControllerBeginAndEndRequestFuncBindMiddleware(t *testing.T) {
app.PartyFunc("/profile/{username}", func(r iris.Party) { app.PartyFunc("/profile/{username}", func(r iris.Party) {
r.Use(middlewareCheck) r.Use(middlewareCheck)
New(r).Register(new(testControllerBeginAndEndRequestFunc)) New(r).Handle(new(testControllerBeginAndEndRequestFunc))
}) })
e := httptest.New(t, app) e := httptest.New(t, app)
@ -231,7 +231,7 @@ func (c *testControllerEndRequestAwareness) EndRequest(ctx context.Context) {
func TestControllerEndRequestAwareness(t *testing.T) { func TestControllerEndRequestAwareness(t *testing.T) {
app := iris.New() app := iris.New()
New(app.Party("/era/{username}")).Register(new(testControllerEndRequestAwareness)) New(app.Party("/era/{username}")).Handle(new(testControllerEndRequestAwareness))
e := httptest.New(t, app) e := httptest.New(t, app)
usernames := []string{ usernames := []string{
@ -287,9 +287,9 @@ func TestControllerDependencies(t *testing.T) {
// test bind value to value of the correct type // test bind value to value of the correct type
myTitleV := testBindType{title: t2} myTitleV := testBindType{title: t2}
m := New(app) m := New(app)
m.AddDependencies(myTitlePtr, myTitleV) m.Register(myTitlePtr, myTitleV)
m.Register(new(testControllerBindStruct)) m.Handle(new(testControllerBindStruct))
m.NewChild(app.Party("/deep")).Register(new(testControllerBindDeep)) m.Clone(app.Party("/deep")).Handle(new(testControllerBindDeep))
e := httptest.New(t, app) e := httptest.New(t, app)
expected := t1 + t2 expected := t1 + t2
@ -349,8 +349,8 @@ func TestControllerInsideControllerRecursively(t *testing.T) {
app := iris.New() app := iris.New()
m := New(app.Party("/user/{username}")) m := New(app.Party("/user/{username}"))
m.AddDependencies(&testBindType{title: title}) m.Register(&testBindType{title: title})
m.Register(new(testCtrl0)) m.Handle(new(testCtrl0))
e := httptest.New(t, app) e := httptest.New(t, app)
e.GET("/user/" + username).Expect(). e.GET("/user/" + username).Expect().
@ -382,7 +382,7 @@ func (c *testControllerRelPathFromFunc) GetSomethingByElseThisBy(bool, int) {} /
func TestControllerRelPathFromFunc(t *testing.T) { func TestControllerRelPathFromFunc(t *testing.T) {
app := iris.New() app := iris.New()
New(app).Register(new(testControllerRelPathFromFunc)) New(app).Handle(new(testControllerRelPathFromFunc))
e := httptest.New(t, app) e := httptest.New(t, app)
e.GET("/").Expect().Status(iris.StatusOK). e.GET("/").Expect().Status(iris.StatusOK).
@ -432,14 +432,14 @@ func (c *testControllerActivateListener) Get() string {
func TestControllerActivateListener(t *testing.T) { func TestControllerActivateListener(t *testing.T) {
app := iris.New() app := iris.New()
New(app).Register(new(testControllerActivateListener)) New(app).Handle(new(testControllerActivateListener))
m := New(app) m := New(app)
m.AddDependencies(&testBindType{ m.Register(&testBindType{
title: "my title", title: "my title",
}) })
m.NewChild(m.Router.Party("/manual")).Register(new(testControllerActivateListener)) m.Party("/manual").Handle(new(testControllerActivateListener))
// or // or
m.NewChild(m.Router.Party("/manual2")).Register(&testControllerActivateListener{ m.Party("/manual2").Handle(&testControllerActivateListener{
TitlePointer: &testBindType{ TitlePointer: &testBindType{
title: "my title", title: "my title",
}, },

View File

@ -16,11 +16,7 @@ import (
func main() { func main() {
app := iris.New() app := iris.New()
app.Logger().SetLevel("debug") app.Logger().SetLevel("debug")
mvc.New(app.Party("/todo")).Configure(TodoApp) mvc.Configure(app.Party("/todo"), TodoApp)
// no let's have a clear "mvc" package without any conversions and type aliases,
// it's one extra import path for a whole new world, it worths it.
//
// app.UseMVC(app.Party("/todo")).Configure(func(app *iris.MVCApplication))
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))
} }
@ -32,20 +28,20 @@ func TodoApp(app *mvc.Application) {
ctx.Next() ctx.Next()
}) })
// Add dependencies which will be binding to the controller(s), // Register dependencies which will be binding to the controller(s),
// can be either a function which accepts an iris.Context and returns a single value (dynamic binding) // can be either a function which accepts an iris.Context and returns a single value (dynamic binding)
// or a static struct value (service). // or a static struct value (service).
app.AddDependencies( app.Register(
sessions.New(sessions.Config{}).Start, sessions.New(sessions.Config{}).Start,
&prefixedLogger{prefix: "DEV"}, &prefixedLogger{prefix: "DEV"},
) )
app.Register(new(TodoController)) app.Handle(new(TodoController))
// All dependencies of the parent *mvc.Application // All dependencies of the parent *mvc.Application
// are cloned to that new child, thefore it has access to the same session as well. // are cloned to that new child, thefore it has access to the same session as well.
app.NewChild(app.Router.Party("/sub")). app.Party("/sub").
Register(new(TodoSubController)) Handle(new(TodoSubController))
} }
// If controller's fields (or even its functions) expecting an interface // If controller's fields (or even its functions) expecting an interface

View File

@ -1,6 +1,7 @@
package mvc package mvc
import ( import (
"github.com/kataras/iris/context"
"github.com/kataras/iris/core/router" "github.com/kataras/iris/core/router"
"github.com/kataras/iris/hero/di" "github.com/kataras/iris/hero/di"
) )
@ -68,7 +69,7 @@ func (app *Application) Configure(configurators ...func(*Application)) *Applicat
return app return app
} }
// AddDependencies adds one or more values as dependencies. // Register appends one or more values as dependencies.
// The value can be a single struct value-instance or a function // The value can be a single struct value-instance or a function
// which has one input and one output, the input should be // which has one input and one output, the input should be
// an `iris.Context` and the output can be any type, that output type // an `iris.Context` and the output can be any type, that output type
@ -77,17 +78,17 @@ func (app *Application) Configure(configurators ...func(*Application)) *Applicat
// //
// These dependencies "values" can be changed per-controller as well, // These dependencies "values" can be changed per-controller as well,
// via controller's `BeforeActivation` and `AfterActivation` methods, // via controller's `BeforeActivation` and `AfterActivation` methods,
// look the `Register` method for more. // look the `Handle` method for more.
// //
// It returns this Application. // It returns this Application.
// //
// Example: `.AddDependencies(loggerService{prefix: "dev"}, func(ctx iris.Context) User {...})`. // Example: `.Register(loggerService{prefix: "dev"}, func(ctx iris.Context) User {...})`.
func (app *Application) AddDependencies(values ...interface{}) *Application { func (app *Application) Register(values ...interface{}) *Application {
app.Dependencies.Add(values...) app.Dependencies.Add(values...)
return app return app
} }
// Register adds a controller for the current Router. // Handle serves a controller for the current mvc application's Router.
// It accept any custom struct which its functions will be transformed // It accept any custom struct which its functions will be transformed
// to routes. // to routes.
// //
@ -98,7 +99,7 @@ func (app *Application) AddDependencies(values ...interface{}) *Application {
// //
// It returns this mvc Application. // It returns this mvc Application.
// //
// Usage: `.Register(new(TodoController))`. // Usage: `.Handle(new(TodoController))`.
// //
// Controller accepts a sub router and registers any custom struct // Controller accepts a sub router and registers any custom struct
// as controller, if struct doesn't have any compatible methods // as controller, if struct doesn't have any compatible methods
@ -131,7 +132,7 @@ func (app *Application) AddDependencies(values ...interface{}) *Application {
// where Get is an HTTP Method func. // where Get is an HTTP Method func.
// //
// Examples at: https://github.com/kataras/iris/tree/master/_examples/mvc // Examples at: https://github.com/kataras/iris/tree/master/_examples/mvc
func (app *Application) Register(controller interface{}) *Application { func (app *Application) Handle(controller interface{}) *Application {
// initialize the controller's activator, nothing too magical so far. // initialize the controller's activator, nothing too magical so far.
c := newControllerActivator(app.Router, controller, app.Dependencies) c := newControllerActivator(app.Router, controller, app.Dependencies)
@ -154,12 +155,18 @@ func (app *Application) Register(controller interface{}) *Application {
return app return app
} }
// NewChild creates and returns a new MVC Application which will be adapted // Clone returns a new mvc Application which has the dependencies
// to the "party", it adopts // of the current mvc Mpplication's dependencies.
// the parent's (current) dependencies, the "party" may be
// a totally new router or a child path one via the parent's `.Router.Party`.
// //
// Example: `.NewChild(irisApp.Party("/path")).Register(new(TodoSubController))`. // Example: `.Clone(app.Party("/path")).Handle(new(TodoSubController))`.
func (app *Application) NewChild(party router.Party) *Application { func (app *Application) Clone(party router.Party) *Application {
return newApp(party, app.Dependencies.Clone()) return newApp(party, app.Dependencies.Clone())
} }
// Party returns a new child mvc Application based on the current path + "relativePath".
// The new mvc Application has the same dependencies of the current mvc Application.
//
// The router's root path of this child will be the current mvc Application's root path + "relativePath".
func (app *Application) Party(relativePath string, middleware ...context.Handler) *Application {
return app.Clone(app.Router.Party(relativePath, middleware...))
}

View File

@ -12,7 +12,7 @@ var defaultSessionManager = sessions.New(sessions.Config{})
// direct access to the current client's session via its `Session` field. // direct access to the current client's session via its `Session` field.
// //
// SessionController is deprecated please use the new dependency injection's methods instead, // SessionController is deprecated please use the new dependency injection's methods instead,
// i.e `mvcApp.AddDependencies(sessions.New(sessions.Config{}).Start)`. // i.e `mvcApp.Register(sessions.New(sessions.Config{}).Start)`.
// It's more controlled by you, // It's more controlled by you,
// also *sessions.Session type can now `Destroy` itself without the need of the manager, embrace it. // also *sessions.Session type can now `Destroy` itself without the need of the manager, embrace it.
type SessionController struct { type SessionController struct {
@ -23,7 +23,7 @@ type SessionController struct {
// BeforeActivation called, once per application lifecycle NOT request, // BeforeActivation called, once per application lifecycle NOT request,
// every single time the dev registers a specific SessionController-based controller. // every single time the dev registers a specific SessionController-based controller.
// It makes sure that its "Manager" field is filled // It makes sure that its "Manager" field is filled
// even if the caller didn't provide any sessions manager via the MVC's Application's `Register` function. // even if the caller didn't provide any sessions manager via the MVC's Application's `Handle` function.
func (s *SessionController) BeforeActivation(b BeforeActivation) { func (s *SessionController) BeforeActivation(b BeforeActivation) {
if didntBindManually := b.Dependencies().AddOnce(defaultSessionManager); didntBindManually { if didntBindManually := b.Dependencies().AddOnce(defaultSessionManager); didntBindManually {
b.Router().GetReporter().Add( b.Router().GetReporter().Add(