Showing posts with label Service. Show all posts
Showing posts with label Service. Show all posts

Monday, July 3, 2017

Laravel 5: Get Service Instance In Controller Dynamically | Get Service Instance In Service Dynamically

The Laravel service container is a powerful tool for managing class dependencies. Dependency injection is a fancy word that essentially means this: class dependencies are "injected" into the class via the constructor.

There are several ways to resolve something out of the container. First, you may use the make method as below example:

$service = app()->make("App\\Service\\EmployeeService");

So it makes life easier.

Friday, June 16, 2017

Laravel 5.X: Access HTTP Request From Controller | Service

It's very important to access HTTP Request from Laravel Controller or Service. Below is a code example showing how to access HTTP Request from Laravel Controller. Same for Service.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request as HttpRequest;
use Illuminate\Routing\Controller as BaseController;

class HomeController extends BaseController
{
    private $HttpRequest;
    public function __construct(HttpRequest $HttpRequest)
    {
        $this->HttpRequest = $HttpRequest;
    }

    public function checkHttpRequest() {
        echo $this->HttpRequest->get("id") . "<BR>";
        echo $this->HttpRequest->getBaseUrl() . "<BR>";
        echo $this->HttpRequest->getUri();
        die();
    }
}









Wednesday, May 25, 2016

Grails create read only service

Full read only service


package com.pkm.services.common

import org.springframework.transaction.annotation.Transactional

@Transactional(readOnly = true)
class DataReadService {
    def a() {

    }

    def b() {

    }
}

Some methods (method a) are read only, others are transactional


package com.pkm.services.common

import org.springframework.transaction.annotation.Transactional

@Transactional
class DataReadService {
    @Transactional(readOnly = true)
    def a() {

    }

    def b() {

    }
}

Monday, June 30, 2014

Grails get bean/service from service or other class

import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib
import grails.util.Holders
import org.codehaus.groovy.grails.commons.GrailsApplication

public static GrailsApplication grailsApplication = Holders.grailsApplication;
public static ServletContext servletContext = Holders.servletContext;
public static ApplicationTagLib g = Holders.applicationContext.getBean("org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib")

def bean = Holders.applicationContext.getBean(beanIdentifier);
// beanIdentifier = userService, groupService etc...

Monday, February 10, 2014

Use grails service from java class


package com.groovy.exception

import com.services.TestService
import org.springframework.context.ApplicationContext
import org.codehaus.groovy.grails.web.util.WebUtils

/**
 * Created by pritom on 9/02/14.
 */
class CustomException extends RuntimeException {
    private static TestService testService;
    String message;
    List args = [];

    public CustomException(String message, List args) {
        this.message = message;
        this.args = args;
    }

    public String getMessage() {
        return this.toString();
    }

    public List getArgs() {
        return this.args;
    }

    public String toString() {
        String _message = testService.getMessage(this.message, this.args);
        return _message
    }

    static {
        if(!testService) {
            ApplicationContext applicationContext = WebUtils.retrieveGrailsWebRequest().getApplicationContext();
            testService = applicationContext.getBean("testService");
        }
    }
}

Thursday, October 3, 2013

Grails Groovy dynamically invokeMethod with empty/single/multi parameters

You need to first get bean object of your service class.
Create a service like below and get your required service by calling:


serviceFinderService.getServiceByName("serviceName");

 If you have a service named "StudentService.groovy" then replace "serviceName" with "Student" or "student".


package com.pritom.services

import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

class ServiceFinderService {
    private static HashMap beanList = new HashMap();
    private def grailsApplication;
    private static def ctx;

    def serviceMethod() {

    }

    public def getServiceByName(String bean) throws Exception {
        if(!ctx) {
            ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
        }
        bean += "Service";
        bean = bean[0].toLowerCase() + bean.substring(1);
        if(beanList.containsKey(bean)) {
            return beanList.get(bean);
        }
        beanList.put(bean, ctx.getBean(bean));
        if(beanList.containsKey(bean)) {
            return beanList.get(bean);
        }
        throw new Exception("Invalid service");
    }
}


Now check and invoke the method if a specific method existing by such way:


def studentService = ServiceFinderService.getServiceByName("Student");

if(studentService.metaClass.respondsTo(studentService, "methodName", [Integer, String, Boolean] as Object[]) {
    def result = studentService.invokeMethod("methodName", [1, "Pritom K Mondal", true] as Object[]);
}

/* If your method is static then call it by: */
if(studentService.metaClass.respondsTo(studentService, "methodName", [Integer, String, Boolean] as Object[]) {
    def result = studentService.metaClass.getTheClass().invokeMethod("methodName", [1, "Pritom K Mondal", true] as Object[]);
}


Wednesday, August 7, 2013

Grails bean/service initialization dynamically to handle circular dependency

Suppose you have a service named OneService and another service named TwoService;
Now if you try to initiate TwoService in OneService and OneService in TwoService then you have some error regarding circular depency.

class OneService {
    def twoService;
}

class TwoService {
    def oneService;
}
To handle this you may need some trick.
First create a private static variable myTwoService and then initiate it when call it.

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA

class OneService {
    def ctx
    private static TwoService myTwoService;

    def getTwoService() {
        if(!ctx) {
            ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
        }
        if(!myTwoService) {
            myTwoService = ctx.getBean("twoService");
        }
        return myTwoService;
    }

    def someFunction = {
        def str = twoService.callSomeFunction();  
        /* it actually call getTwoService */
    }
}
And change you TwoService to call OneService such this way.

How do I get an instance of a Grails service programmatically

The Grails documentation describes a way to get a service when in a servlet. This might be useful, if you can obtain the same objects in your context:

ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext();
CountryServiceInt service = (CountryServiceInt) ctx.getBean("countryService");
String str = service.sayHello("Some String!");

Sunday, July 28, 2013

How do I call/use Grails service from a gsp

We can use 'grailsApplication.classLoader.loadClass' to load service.

<%@ page import="com.myproject.MyService" %>
<%
def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
%>
<span>${myService.methodName()}</span>


We can use another approach

In Grails we can use the set tag to define a variable with a value on a GSP. But we can also use the same tag to access a Grails service on a GSP. We must use the bean attribute with the name of the Grails service. We can even pass the name of any Spring managed bean in the application context of our application.
In the following sample GSP we access a Grails service with the name BlogService. We invoke the method allTitles() and use the result.

<html>
<head>
<meta content="main" name="layout"/>
</head>
<body>
    %{--Use BlogService--}%
    <g:set var="blog" bean="blogService"/>
    <ul>
    <g:each in="${blog.allTitles()}" var="title">
        <li>${title}</li>
    </g:each>
    </ul>
</body>
</html>