Best way to define globals in a Play! 2.0 application - scala

In Play! 2.0, one can use Global as documented here. Global needs to be in the default (empty) package.
I also need globals in my application, and some of them need to be available to the methods in Global. Thus, I put them in Global.scala like so:
package object globals {
lazy val foo = Play.maybeApplication.flatMap(_.configuration.getString("foo")).getOrElse("default_value_of_foo")
}
And then I use it in my controllers like this:
globals.foo
Is there a better way?

I think this question is more about general software design than it is about Play Framework. If you truly need a bunch of random properties why not create your own object?
object Configuration {
val timeout = Play.maybeApplication.flatMap(
_.configuration.getString("timeout")
).getOrElse(0))
}
But usually the values belong to some other logical entity that is being configured.

I had problems using Global as a singleton for my app. I think you will have some problems too to access the singleton from your controllers (see this post).
But you can create your own singleton in one of your packages and access it as you plan to do.

Related

AS3 targeting controller class variable using string

I'm looking for a way of condensing some of my AS3 code to avoid almost duplicate commands.
The issue is that I have multiple variables with almost the same name e.g. frenchLanguage, englishLanguage, germanLanguage, spanishLanguage
My Controller class contains public static variables (these are accessed across multiple classes) and I need a way to be able to call a few of these variables dynamically. If the variables are in the class you are calling them from you can do this to access them dynamically:
this["spanish"+"Language"]
In AS3 it's not possible to write something like:
Controller.this["spanish"+"Language"]
Is there any way to achieve this? Although everything is working I want to be able to keep my code as minimal as possible.
It is possible to access public static properties of a class this way (assuming the class name is Controller as in your example:
Controller['propertyName']
I'm not sure how this helps to have "minimal code", but this would be a different topic/question, which might need some more details on what you want to achive.
Having said that, I like the approach DodgerThud suggests in the comments of grouping similar values in a (dynamic) Object or Dictonary and give it a proper name.
Keep in mind, that if the string you pass in as the key to the class or dynamic object is created from (textual) user input you should have some checks for the validity of that data, otherwise your programm might crash or expose other fields to the user.
It would make sense to utilize a Dictionary object for a set of variables inherited: it provides a solid logic and it happens to work...
I do not think this is what you are trying to accomplish. I may be wrong.
Classes in AS3 are always wrapped within a package - this is true whether you have compiled from Flash, Flex, Air, or any other...
Don't let Adobe confuse you. This was only done in AS3 to use Java-Based conventions. Regardless, a loosely typed language is often misunderstood, unfortunately. So:
this["SuperObject"]["SubObject"]["ObjectsMethod"][ObjectsMethodsVariable"](args..);
... is technically reliable because the compiler avoids dot notation but at runtime it will collect a lot of unnecessary data to maintain those types of calls.
If efficiency becomes an issue..
Use:
package packages {
import flash.*.*:
class This implements ISpecialInterface {
// Data Objects and Function Model
// for This Class
}
package packages {
import...
class ISpecialInterface extends IEventDispatcher

Where do I put shared model and controller logic?

I've just started using Sails and I have a couple models with the same method defined multiple times. Is there a way to share logic between models? Like having a "Base" model from which other models inherit behaviour?
Same question for controllers. Is there a way to setup an "ApplicationController" or a system of inheritance?
Agree with Yedhu, however You can also create defaults and extend using lodash
var = defaultModel = require('./<LOCATION OF DEFAULT MODEL DEFINITION>/defaultModel');
module.exports.models = _.merge({
// .. defign your model here like your normally would
}, defaultModel)
I am new to Sails JS, started just two months back.
Not particularly for Models or Controllers. But still shared logic can go to Services. I use this when I need to access the same code from multiple places within the application.

is it possible to load scala classes "dynamic"? (like pythons import_module)

at the moment I'm try to write an API with Scala. This API should handle file backends, like Smb, S3, FileSystem Storage, etc.
So I wrote some classes like Storage which is a base class for storage backends and the Subclasses like FileSystemStorage, SmbStorage which subclasses Storage but from now on, i want to use those classes if i specify them in a settings file.
I wanted it like it is in Django: https://docs.djangoproject.com/en/1.6/ref/settings/#std:setting-DEFAULT_FILE_STORAGE Where i could specifiy a string, to my default storage engine.
And then it should "magically" work so that I could use DefaultStorage to access either FileSystemStorage or SmbStorage also it should be possible to create more "storage" classes. is this even possible?
Currently I have something in my mind how i could realize this, but I'm unsure if this is good practice in scala.
JVM classes are already loaded dynamically. What you want is to choose an instance dynamically.
You can do something like:
def byName(name:String) = name match {
"FileSystemStorage" => FileSystemStorage
"SmbStorage" => SmbStorage
}
I am assuming these are objects. If they are classes, just add a new keyword.
Now, if the class name is unknown at compile time you can do Class.forName(full_qualified_classname). But this will give you a Class object, not the instance for the class, in which case you will need to invoke newInstance (assuming it has an argument-less constructor). The way you described your problem suggests you don't want this approach.

IOC vs New guidelines

Recently I was looking at some source code provided by community leaders in their open source implementations. One these projects made use of IOC. Here is sample hypothetical code:
public class Class1
{
private ISomeInterface _someObject;
public Class1(ISomeInterface someObject)
{
_someObject = someObject;
}
// some more code and then
var someOtherObject = new SomeOtherObject();
}
My question is not about what the IOCs are for and how to use them in technical terms but rather what are the guidelines regarding object creation. All that effort and then this line using "new" operator. I don't quite understand. Which object should be created by IOC and for which ones it is permissible to be created via the new operator?
As a general rule of thumb, if something is providing a service which may want to be replaced either for testing or to use a different implementation (e.g. different authentication services) then inject the dependency. If it's something like a collection, or a simple data object which isn't providing behaviour which you'd ever want to vary, then it's fine to instantiate it within the class.
Usually you use IoC because:
A dependency that can change in the future
To code against interfaces, not concrete types
To enable mocking these dependencies in Unit Testing scenarios
You could avoid using IoC in the case where you don't control the dependency, for example an StringBuilder is always going to be an StringBuilder and have a defined behavior, and you usually don't really need to mock that; while you might want to mock an HttpRequestBase, because it's an external dependency on having an internet connection, for example, which is a problem during unit tests (longer execution times, and it's something out of your control).
The same happens for database access repositories and so on.

Can I set the Database adapter to use permanently from within a Zend_Db_Table_Abstract Class?

I have 2 databases that my site uses including a central user database that relates to other site-specific databases.
Sometimes it is adequate to call new User(array('db'=>'adapter1')); (but never convenient); other times, though, such as when declaring relationships between tables on different databases, there is no way to do this.
Does anyone know a way to specify which database adapter to use from within the Zend_Db_Table_Abstract class?
Thanks!
Getting back to this pretty late, but none of the answers here quite did it for me. A select few of my database models needed to use 'tdb' and the following code was added to each of those classes to have that happen automatically:
protected function _setupDatabaseAdapter()
{
$this->_db = Zend_Registry::get('tdb');
parent::_setupDatabaseAdapter();
}
I thank you all for your suggestions along the way!
Zend_Db_Table_Abstract provides a static method to set the default database adapter. Do this as follows:
Zend_Db_Table_Abstract::setDefaultAdapter($adapter);
Now, all your Table objects will use your adapter by default.
Note: the online docs sometimes don't make this obvious, so your second best place to check is in the API here: http://framework.zend.com/apidoc/core/
You could set the class variable $_db to the correct adapter in the constructor.
global $adapter1; //There are better ways than using a global variable
$this->_db = $adapter1;
Assuming the adapter object can be referenced in the constructor. That doesn't seem to portable, but I believe it would work.
The init function can be used, it is not used in Zend_Db_Adapter_Abstract, can be used in your class to setup whatever needs to be done. _setAdapter accepts a string naming a Registry Key.
public function init()
{
$this->_setAdapter('tdb');
}