2016-06-12 4 views
0

に共通の機能を呼び出す私がプレイFrameworkの次のアクションを持っている:はプレイ

def action = Action { request => 

    common1() // this is common to all the actions 

    // some functions specific to the action 

    var json = common2() // this is common to all the actions 

    Ok(json) 
    } 

は、私は自分のアプリケーションで多くのアクションを持っています。私の問題は、すべてのアクションでcommon1common2が呼び出されているため、呼び出しを繰り返したくないということです。このシナリオを処理するには、どのような良い方法がありますか?

+0

が重複する可能性を:アクション構成を実装する方法](http://stackoverflow.com/questions/25105558/play-how-to-implement-action-composition) – cchantep

答えて

1

のHttpフィルタ

何かがすべてのアクションで呼び出された場合は、フィルタを見てみることをお勧めします:上記のリンクからhttps://www.playframework.com/documentation/2.5.x/ScalaHttpFilters

例:

class LoggingFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter { 

    def apply(nextFilter: RequestHeader => Future[Result]) 
      (requestHeader: RequestHeader): Future[Result] = { 

    val startTime = System.currentTimeMillis 

    nextFilter(requestHeader).map { result => 

     val endTime = System.currentTimeMillis 
     val requestTime = endTime - startTime 

     Logger.info(s"${requestHeader.method} ${requestHeader.uri} took ${requestTime}ms and returned ${result.header.status}") 

     result.withHeaders("Request-Time" -> requestTime.toString) 
    } 
    } 
} 

アクション作曲:

上記のリンクからhttps://www.playframework.com/documentation/2.5.x/ScalaActionsComposition

例:あなたは、特定のアクションのために特定のコードを実行するいくつかのものは、あなた自身のActionFitlers、ActionRefinersなどを作成

object LoggingAction extends ActionBuilder[Request] { 
    def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { 
    Logger.info("Calling action") 
    block(request) 
    } 
} 

使用法:[再生の

def index = LoggingAction { 
    Ok("Hello World") 
} 
+0

感謝、アクション構成はおそらく私が必要としているものです。どのようにオブジェクトを 'invokeBlock'から' index'メソッドに渡すことができますか? – ps0604

+0

独自のリクエストタイプを作成し、必要な情報を入力して充実させます。 – rethab