I want to implement a language Setter for all Controllers and need to run this method before the Routing to the Controller -> the front Controller.
If have implemented a method in my Controller Class, but for some usages it must be run earlier before controller initilisation
class Controller extends CController
{
public function __construct($id, $module = null)
{
// Set the application language
if (isset($_GET['language']))
{
$lang = $_GET['language'];
You could use the onBeginRequest event of the application. This usually requires you to add some code to your index.php. Here's a quick example:
$app = Yii::createWebApplication($config);
$app->onBeginRequest = function($event) {
// ... whatever you want to do
}
$app->run();
Of course instead of a closure function you can also attach any other valid callback.
You can override beforeAction($action)
class Controller extends CController
{
public function beforeAction($action)
{
$language = !empty($_GET['lang']) ? $_GET['lang'] : 'en';
return parent::beforeAction($action);
}
}
Related
I'm using JavaFX, where you create a class that extends JavaFX Application, and then you pass the class to JavaFX's launch method. Inside the Application class you override the start method which gets an instance of Stage passed into it.
How can I make this instance of Stage available as a dependency for other objects?
// Kotlin
fun main() {
launch(MyApplication::class.java)
}
class MyApplication : Application()
{
override fun start(stage: Stage)
{
// I want other objects to be able to have stage injected into them.
val myWindow = MyWindow
stage.run {
scene = Scene(myWindow, 800.0, 600.0)
show()
}
}
}
In Spring I think you would do something like this
// Java
Object externalyDefinedBean = ...;
GenericApplicationContext parentContext = new StaticApplicationContext();
parentContext.getBeanFactory().registerSingleton("injectedBean", externalyDefinedBean);
I am using NestJS with Swagger Module to produce the equivalent API Spec.
Is there a way to disable security for a specific controller method, while having marked the Controller class as requiring authentication?
Example:
// apply bearer auth security to controller
#ApiBearerAuth()
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
// How can **getHello** method be made public???
#Get()
getHello(): string {
return this.appService.getHello();
}
}
I am looking for a more intuitive way compared to the straightforward one where each controller method should be mark with security except for the public ones....
I have tried using #ApiOperation({ security: [] }) without any result. It still get's the security definition from the controller class
It seems after all that this has been already discussed and will not be implemented: github.com/nestjs/swagger/issues/1319
#ApiBearerAuth() support Controller and function. You should put #ApiBearerAuth() into what function you need
// apply bearer auth security to controller
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
// How can **getHello** method be made public???
#Get()
getHello(): string {
return this.appService.getHello();
}
#ApiBearerAuth() <---- here
#Post()
createHello(): string {
return this.appService.createHello();
}
}
At example I have three classes : View , FView ( extends View) and MView (extends View) . I have variable from type MView and want to to check it against parent class View ( i.e if this variable is from class View ). Is it possible to get the parent class ( View class) ? . Here is full example: https://try.haxe.org/#eA594
class Test {
static function main() {
var v = new SView();
trace(Type.getClassName( Type.getSuperClass(Type.getClass(v))) );
}
}
class View :
class View {
public function new() {
}
}
class FView :
class FView extends View {
public function new() {
super();
}
}
class SView :
class SView extends FView {
public function new() {
super();
}
}
If you want to get to the base class, you can simply recurse or iterate until Type.getSuperClass() returns null:
// at runtime: find out what is the base class of `v`
var base:Class<Dynamic> = Type.getClass(v);
while (true) {
var s = Type.getSuperClass(base);
if (s == null)
break;
base = s;
}
trace(Type.getClassName(base));
However, you mention that you want to do this simply to check if MView (or SView) are of the View type.
Well, for this, there are a few simpler alternatives...
First, at compile type, you can simply use a type check (or an assignment) to check if v:SView unifies with View:
// at compile time: enforce that `v` be of type `View` or compatible with it
var v1 = (v:View); // use a type check
var v2:View = v; // or simply pass it to something expecting `View`
If you need to do it at runtime, that's possible as well with Std.is():
// at runtime: check if `v` is a subclass instance of `View`
trace(Std.is(v, View));
For a complete example, check out this Try Haxe instance.
I am looking for specialized singleton implementation, probably I might be using wrong terminology and hence looking for expert suggestion. Here is my scenario:
There is common code which can be called by ComponentA or ComponentB. I need to push telemetry data from the common code. Telemetry needs to have information that whether this common code get called by ComponentA or ComponentB.
So common code will have just this line of code:
telemetry.pushData(this._area, data);
where this._area tells the telemetry data is getting pushed for which component
I need to push telemetry data from multiple places so it would be good if object got created once and used through out the code lifetime
One option I can think of passing component context to the common code which in mind doesn't look right, hence looking for suggestion what kind of pattern one should use in this case?
This is what I am thinking
// Telemetry.ts file present in shared code
export class Telemetry extends Singleton {
public constructor() {
super();
}
public static instance(): Telemetry {
return super.instance<Telemetry>(Telemetry);
}
public publishEvent(data): void {
if (!this.area) {
throw new Error("Error: Initialize telemetry class with right area");
}
pushtelemetryData(this.area, data);
}
public area: string;
}
// Create Telemetry object from component A
Telemetry.instance().area = "ComponentA";
// Shared code will call telemetry publishEvent
Telemetry.instance().publishEvent(data);
Thanks
It's not a good pattern to use in TypeScript where you would generally inject dependencies.
If you must absolutely do it then you can do it by faking it somewhat:
namespace Telemetry {
var instance : SingletonSomething;
export function push(data: Any) : void {
if (instance == null) {
instance = new SingletonSomething();
}
instance.push(data);
}
class SingletonSomething() { ... }
}
and then you could call
Telemetry.push(data);
You can imitate the singleton pattern in typescript easily:
class Telemetry {
private static instance: Telemetry;
public static getInstance(): Telemetry {
if (Telemetry.instance == null) {
Telemetry.instance = new Telemetry();
}
return Telemetry.instance;
}
...
}
If you have your code in some sort of closure (module, namespace, etc) then you can replace the static member with:
let telemetryInstance: Telemetry;
export class Telemetry {
public static getInstance(): Telemetry {
if (telemetryInstance == null) {
telemetryInstance = new Telemetry();
}
return telemetryInstance;
}
...
}
But then you can also replace the static method with:
let telemetryInstance: Telemetry;
export function getTelemetryInstance(): Telemetry {
if (telemetryInstance == null) {
telemetryInstance = new Telemetry();
}
return telemetryInstance;
}
export class Telemetry {
...
}
At this point, in case you are using some sort of closure, you might ask yourself if you really need the class at all?
If you use this as a module:
// telemetry.ts
export interface TelemetryData {
...
}
export function pushData(data: TelemetryData): void {
...
}
Then you get exactly what you're looking for, and this is more of the "javascript way" of doing it.
Edit
In the telemetry module there's no need to know the users of it.
If the Telemetry.pushData function needs to have information about the object that called it then define an interface for it:
// telemetry.ts
export interface TelemetryData {
...
}
export interface TelemetryComponent {
name: string;
...
}
export function pushData(data: TelemetryData, component: TelemetryComponent): void {
...
}
Then in the other modules, where you use it:
// someModule.ts
import * as Telemetry from "./telemetry";
class MyComponent implement Telemetry.TelemetryComponent {
// can also be a simple string property
public get name() {
return "MyComponent";
}
fn() {
...
Telemetry.pushData({ ... }, this);
}
}
2nd Edit
Because you are using a module system, your module files are enough to make singletons, there's no need for a class to achieve that.
You can do this:
// telemetry.ts
let area: string;
export interface TelemetryData {
...
}
export function setArea(usedArea: string) {
area = usedArea;
}
export function pushData(data: TelemetryData): void {
...
}
Then:
Telemetry.setArea("ComponentA");
...
Telemetry.publishEvent(data);
The telemetry module will be created only once per page, so you can treat the entire module as a singleton.
Export only the functions that are needed.
So I wanted to isolate controllers from models in testing so that I could easily figure out stuff if troubles arise. Before, I just hit the endpoints with mock data but it was difficult to troubleshoot because the test runs from the router all the way to the datastore. So I'm thinking maybe I'll just create two versions(MockController vs Controller) for each controller(and model) and use one depending on the value of the mode variable. In a nutshell, this is how I plan to implement it.
const mode string = "test"
// UserModelInterface is the Interface for UserModel
type UserModelInterface interface {
Get()
}
// UserControllerInterface is the Interface for UserController
type UserControllerInterface interface {
Login()
}
// NewUserModel returns a new instance of user model
func NewUserModel() UserModelInterface {
if mode == "test" {
return &MockUserModel{}
} else {
return &UserModel{}
}
}
// NewUserController returns a new instance of user controller
func NewUserController(um UserModelInterface) UserControllerInterface {
if mode == "test" {
return &MockUserController{}
} else {
return &UserController{}
}
}
type (
UserController struct {um UserModelInterface}
UserModel struct {}
// Mocks
MockUserController struct {um UserModelInterface}
MockUserModel struct {}
)
func (uc *UserController) Login() {}
func (um *UserModel) Get() {}
func (uc *MockUserController) Login() {}
func (um *MockUserModel) Get() {}
func main() {
um := NewUserModel()
uc := NewUserController(um)
}
This way I could just skip sql query in the MockUserController.Login() and only validate the payload and return a valid response.
What do you think of this design? Do you have a better implementation in mind?
I would let the code that calls NewUserController() and NewUserModel() decide whether to create a mock or real implementation. If you use that pattern of dependency injection all the way up to the top your code will become clearer and less tightly coupled. E.g. if the user controller is used by a server, it would look something like along the lines of:
Real:
u := NewUserController()
s := NewServer(u)
In tests:
u := NewMockUserController()
s := NewServer(u)
I would try a more slim variant spread over a models and a controllers package, like this:
// inside package controllers
type UserModel interface {
Get() // the methods you need from the user model
}
type User struct {
UserModel
}
// inside package models
type User struct {
// here the User Model
}
// inside package main
import ".....controllers"
import ".....models"
func main() {
c := &controllers.User{&models.User{}}
}
// inside main_test.go
import ".....controllers"
type MockUser struct {
}
func TestX(t *testing.T) {
c := &controllers.User{&MockUser{}}
}
For controller testing consider the ResponseRecorder of httptest package