How to DRY optional app feature in Laravel context - laravel

For example we have two features: Access Groups, Target Groups and there may be added others in future.
Also we have Company entity to which User entity related 1:M (Company to User).
So in different places of the codebase we need to check if some of these features enabled for Company (as well for User): in Request classes, Query classes (i.e. Repositories, Queries, or even Models, depends on your chooses), Actions/Commands/Services, etc.
Clearly everywhere repeated checking like below isn't accepted by DRY.
if ($user->company->access_groups_feature_enabled) {
...
} else {
...
}
There must be one place with checking if one or another feature is enabled/disabled, in the same place we should choose correct Requests/Services/Repositories/etc, so if feature Access Groups enabled we should load RequestImplyingAccessGroups, SomeEntityLikeUserRepositoryImplyingAccessGroup, ShowNewsServiceImplyingAccessGroups, and so on (please don't bother about naming, it's just for example to understand what I mean).
The same is for Target Groups and other features. Then we should use these classes by common interface dependency-injecting them to agnostic classes somehow.
I think it may be done on Middleware level but I'm a little bit confused right now.
Are there any best practice for such case? How did you implement it in your projects?
Also I found Fowler's article about that: https://martinfowler.com/articles/feature-toggles.html
But I think I am a little bit confused to apply it for laravel infrastructure.

Related

Should I Nest Routes to Resources in Laravel?

This may be a little subjective, but I feel that best-practice must exist (or even good design when it comes to Laravel apps). Googling results in lots of things that are not to do with the actual points in this question.
Say I am building a web application that has teams, which may have projects, which may have documents.
Should I design the routing so that documents are within the path of the projects they belong to, which are then within the path of the teams they belong to, or keep things at a top level?
As far as I can tell, there are two ends to this spectrum that are worth discussing (other options are just the grey in-between):
Nesting
Example, Doc C is found at: /teams/team-a/projects/project-b/documents/doc-c
It is easy to do this, and in the routing file, I can use route groups to help keep the structure clean. I think it's more logical and perhaps more convenient for the user (they can work out URLs for themselves!). My concerns are that I am importing complexity into each page request:
in checking that the route has integrity (i.e., that doc-c does belong to project-b), and
that the user has authority to access each of the nested assets all the way through the route.
Should I be putting gates/policy checks for every resource at the beginning of each controller method, for every route parameter? Otherwise, where can this be abstracted?
And regarding route integrity, I've never seen examples testing for this - so is this not a common approach? If we don't verify route integrity, then a page could show mixed information by hacking the route (e.g.,/teams/team-a/projects/project-Z/documents/doc-c, would show info about project Z on doc-c's page).
Without Nesting
Example, Doc C is found at : /documents/doc-c
In this example, every asset would have its own base route, more like an API I guess.
No integrity checks required, and the controller would pre-determine the other assets shown to generate the view.
But is this UX good enough? The majority of websites I've seen do not do this.
This is an interesting question - as you mentioned, it may be a little subjective, but worth the discussion.
You touch on a few points, so I will attempt to address them separately.
Nesting vs Not nesting
First thing to clear up in my opinion is browser routes versus API routes. If you are providing an API - either internally to your app or externally to the public, I would avoid nested routes for a few reasons:
resource/id format is quite standard and expressive for API's
this makes it easier to document
this makes it easier for the consumer app to dynamically construct API requests
However, your question does seem to focus on the browser routes. In my opinion browser routes can and should be whatever reads nicely - the url, especially these days, can be considered as part of the UI. For example, you may go to settings (and I would expect to see /settings), from the settings page, if I were to go into the notifications settings section, I would expect to see /settings/notifications.
The routes act and assist with UX - they are almost a breadcrumb and should look as such.
So, I would definitely nest for browser routes, and would definitely not for APIs.
Route integrity
The real heart of your question I think is about the route integrity. I think regardless if you choose to nest or not you need to be checking your permissions with the assumption that someone is tampering with the urls - the same way you assume that the user has tampered with the form input.
Essentially your routes (nested or not) act as input, and you will need to validate that. Route level middleware is one approach, but is often too generic to solve anything complex so you may find it easier to tackle it with controller middleware (https://laravel.com/docs/5.7/controllers#controller-middleware).
So you may do something like:
public function __construct()
{
$this->middleware('auth');
$this->middleware('canViewProject')->only('show');
$this->middleware('canEditProject')->except('store');
}
Whether you use Gates, Policies or just plain old middleware will probably depend on the complexity of the project - but the above applies regardless - treat the urls as input and validate accordingly
I've spent the last year looking at this and refining it, and stumbled upon an elegant solution recently. Nesting can be done nicely, I'm sticking to resource controllers and dot-syntax for nested route resources.
In order to enforce the route validation, I am using something like the following. There is a good answer here, which suggests explicitly binding the models in question.
So with
Route::resource('posts.comments', 'CommentsController');
You'd use
Route::bind('comment', function ($comment, $route) {
return Comment::where('post_id', $route->parameter('post'))->findOrFail($comment);
});
This will automatically work everywhere. If required, you could test for the upstream parameter to be found, and only perform the test in those cases (e.g. to cater for routes where only a comment is specified).
So much work has been subsequently done on Laravel. My default response to this is "yes, use route nesting". I keep routes restful, using (nested) resource controllers wherever possible, and single-action controllers for the odd use case. Route scoping is even automatic now, if specified correctly.
This always has been a discussion between developers even the creators of Laravel have this argument, so what is the good practice?
Lately I've seen a tweet from Taylor Otwell saying that he has deprecated the
nested routes section from Laravel docs because he didn't prefer it, while when you open Laracasts you see Jeffrey is implementing this concept like /series/php-testing/episodes/hello-world.
As I told it's a quiet argument and when it comes to choices like that I always do what it feels good for me. So if I were you I wouldn't nest neither teams or projects but maybe I would nest projects/documents, I don't go for nesting always.
This might be a bit of a deviation from the original question, but I feel that Adam Wathan's Laracon US 2017 talk might be a useful resource for this discussion. (https://www.youtube.com/watch?v=MF0jFKvS4SI)
I am relatively new to development and therefore explore a lot of code bases on github. I always struggle to understand nested routes. So as a best practice I would prefer no-nesting to nesting.
Keeping stuff "CRUDY by design" as Adam calls it, one thing you achieve, imo, is simplification of route names. If I were to work in a group, that is a pattern I would prefer.
However, referring to the penultimate paragraph on your question, I struggle to understand why an integrity check is not needed.
I think you should makes use of Role concepts, Route grouping , Middleware concepts to build this app
For Role related things check https://github.com/spatie/laravel-permission , a good package
Eg:
Route::group(['middleware' => ['role:super-admin']], function () {
//
});
You can almost do any role, permission related things using above package.
Assume roles like project manager, developer.
Group your Routes based on roles & assign proper Middleware as you need.
For URL : /teams/team-a/projects/project-b/documents/doc-c
Check the Authenticated user has a role in team-a & project-b (You can check this in Middleware, Controller or custom Service provider anywhere as your need).
Also just check https://laravelvoyager.com/
Thanks

Codeigniter when to create new controllers/models

I have watched many youtube guides/tutorials but those only tackle the coding part.
Whenever i start a project, i always start with a simple controller called main.
and 2 models.
For example: if i were to start an online store project. Then my models would be 'product_model' and 'user_model'. All database functions for users, i always put them in the 'user_model' and all database functions for products, i always put them in the 'product_model'.
user_model:
public function register(){
}
public function login(){
}
//more functions for user
product_model:
public function create_product(){
}
public function review_product(){
}
//more functions for product
My problem is that i easily get confused with my project and/or dissatisfied with how unorganized it is. especially when im more than halfway into the project and i accumulate hundreds of lines of codes.
I could try to organize them myself but at the end of the day, i'm just an amateur so i end up doubting myself. so i get no work done for 1 day(or doing work but redoing it again and again). then that snowballs to tomorrow and the day after that and so on and so forth.
So i want to ask to experienced programmers a basic guideline for me, when to create a new model and a new controller?
How do i group up functions and make them into a separate model?
Do i make a new model per table? and all database functions to that table i just write in the new model created for that table?
Or
Do i group up database functions based on what they do? for example: purchasing a product involves many separate database functions. so save them all inside purchase_model?
The answer to all of these questions is: it depends. Personally I think that kindof of flexibility is what makes coding so interesting.
As a general rule of thumb I try to keep all my classes less than 500-700 lines of code and functions less than 20 lines of code. If my class becomes larger than that I usually start a new one. With that being said, controllers I am fine with being larger as form validation and response logic can take up quite a few lines.
So let's take an example: user authentication system
I would have a controller that contains functions for login, registration, forgot password, and activation; another controller for user management that contains functions to delete, ban, unban, activate, and create new users; and then another controller for the users' profile that contains functions for editing their details and profile picture.
Now as user management and auth systems are typically reusable a library is better then using a model or models; but let's say we use models. I would have a model for each of the controllers outlined in the aforementioned paragraph and then a model for general "utility" functions like checking if the user is logged in .etc.
Generally
You have to decide:
How much code is too much for a controller/model?
(with above) Do I expect my code to grow? If so then I have to take into account how much when determining (1).
How should I group together functions? For this keep in mind separation of concerns e.g. auth functions shouldn't be grouped with database backup functions.
Am I doing too much in a particular function/model? If so, how should I separate these items so that I conform with DRY principles (chances are some code is reusable elsewhere even though its functionality is inherently different).
(with above) If this code is really that useful elsewhere, should I make it into a library/helper?
(and there are countless other things to take into consideration).
I think it is important to realize (especially as a beginner) that your coding style and the "techniques" and organization skills you use will be constantly evolving and so will your code. While it is nice to see that you want to learn the best practices - a lot of this will be dependent on what you want to achieve with your app and what level of mastery you are at in your coding career. Try and look at the bigger picture and realize in a year or two when you look at your code again you will probably say "what was I even thinking here?".
Side note: you could research the ORM approach to models (Laravel and a host of other frameworks use it) but CI has a more "whatever" approach to just about everything. If being forced to work a certain way makes you feel more secure, you might want to learn other "more advanced" and "newer" frameworks.

Laravel Repository pattern and many to many relation

In our new project we decided to use hexagonal architecture. We decided to use repository pattern to gain more data access abstraction. We are using command bus pattern as service layer.
In our dashboard page we need a lot of data and because of that we should use 3 level many to many relations (user -> projects -> skills -> review) and also skills should be active(status=1).
The problem rises here, where should i put this?
$userRepository->getDashboardData($userId).
2.$userRepository->getUser($userId)->withProjects()->withActiveSkills()->withReviews();
3.$user = $userRepository->getById();
$projects = $projectRepository->getByUserId($user->id);
$skills = $skillRepository->getActiveSkillsByProjectsIds($projectIds);
In this case, I couldn't find the benefits of repository pattern except coding to interface which can be achived with model interfac.
I think solution 3 is prefect but it adds a lot of work.
You have to decide (for example) from an object-oriented perspective if a "User" returned is one that has a collection of skills within it. If so, your returned user will already have those objects.
In the case of using regular objects, try to avoid child entities unless it makes good sense. Like, for example.. The 'User' entity is responsible for ensuring that the child entities play by the business rules. Prefer to use a different repository to select the other types of entities based on whatever other criteria.
Talking about a "relationship" in this way makes me feel like you're using ActiveRecord because otherwise they'd just be child objects. The "relationship" exists in the relational database. It only creeps into your objects if you're mixing database record / object like with AR.
In the case of using ActiveRecord objects, you might consider having specific methods on the repository to load the correctly configured member objects. $members->allIncludingSkills() or something perhaps. This is because you have to solve for N+1 when returning multiple entities. Then, you need to use eager-loading for the result set and you don't want to use the same eager loading configuration for every request.. Therefore, you need a way to delineate configurations per request.. One way to do this is to call different methods on the repository for different requests.
However, for me.. I'd prefer not to have a bunch of objects with just.. infinite reach.. For example.. You can have a $member->posts[0]->author->posts[0]->author->posts[0]->author->posts[0].
I prefer to keep things as 'flat' as possible.
$member = $members->withId($id);
$posts = $posts->writtenBy($member->id);
Or something like that. (just typing off the top of my head).
Nobody likes tons of nested arrays and ActiveRecord can be abused to the point where its objects are essentially arrays with methods and the potential for infinite nesting. So, while it can be a convenient way to work with data. I would work to prevent abusing relationships as a concept and keep your structures as flat as possible.
It's not only very possible to code without ORM 'relationship' functionality.. It's often easier.. You can tell that this functionality adds a ton of trouble because of just how many features the ORM has to provide in order to try to mitigate the pain.
And really, what's the point? It just keeps you from having to use the ID of a specific Member to do the lookup? Maybe it's easier to loop over a ton of different things I guess?
Repositories are really only particularly useful in the ActiveRecord case if you want to be able to test your code in isolation. Otherwise, you can create scopes and whatnot using Laravel's built-in functionality to prevent the need for redundant (and consequently brittle) query logic everywhere.
It's also perfectly reasonable to create models that exist SPECIFICALLY for the UI. You can have more than one ActiveRecord model that uses the same database table, for example, that you use just for a specific user-interface use-case. Dashboard for example. If you have a new use-case.. You just create a new model.
This, to me.. Is core to designing systems. Asking ourselves.. Ok, when we have a new use-case what will we have to do? If the answer is, sure our architecture is such that we just do this and this and we don't really have to mess with the rest.. then great! Otherwise, the answer is probably more like.. I have no idea.. I guess modify everything and hope it works.
There's many ways to approach this stuff. But, I would propose to avoid using a lot of complex tooling in exchange for simpler approaches / solutions. Repository is a great way to abstract away data persistence to allow for testing in isolation. If you want to test in isolation, use it. But, I'm not sure that I'm sold much on how ORM relationships work with an object model.
For example, do we have some massive Member object that contains the following?
All comments ever left by that member
All skills the member has
All recommendations that the member has made
All friend invites the member has sent
All friends that the member has established
I don't like the idea of these massive objects that are designed to just be containers for absolutely everything. I prefer to break objects into bits that are specifically designed for use-cases.
But, I'm rambling. In short..
Don't abuse ORM relationship functionality.
It's better to have multiple small objects that are specifically designed for a use-case than a few large ones that do everything.
Just my 2 cents.

Streamlining the implementation of a Repository Pattern and SOA

I'm working with Laravel 5 but I think this question can be applied beyond the scope of a single framework or language. The last few days I've been all about writting interfaces and implementations for repositories, and then binding services to the IoC and all that stuff. It feels extremely slow.
If I need a new method in my service, say, Store::getReviews() I must create the relationship in my entity model class (data source, in this case Eloquent) then I must declare the method in the repo interface to make it required for any other implementation, then I must write the actual method in the repo implementation, then I have to create another method on the service that calls on the repo to extract all reviews for the store... (intentional run-on sentence) It feels like too much.
Creating a new model now isn't as simple as extending a base model class anymore. There are so many files I have to write and keep track of. Sometimes I'll get confused as of to where exactly I should put something, or find halfway throught setting up a method that I'm in the wrong class. I also lost Eloquent's query building in the service. Everytime I need something that Eloquent has, I have to implement it in the repo and the service.
The idea behind this architecture is awesome but the actual implementation I am finding extremely tedious. Is there a better, faster way to do things? I feel I'm beeing too messy, even though I put common methods and stuff in abstract classes. There's just too much to write.
I've wrestled with all this stuff as I moved to Laravel 5. That's when I decided to change my approach (it was tough decision). During this process I've come to the following conclusions:
I've decided to drop Eloquent (and the Active Record pattern). I don't even use the query builder. I do use the DB fascade still, as it's handy for things like parameterized query binding, transactions, logging, etc. Developers should know SQL, and if they are required to know it, then why force another layer of abstraction on them (a layer that cannot replace SQL fully or efficiently). And remember, the bridge from the OOP world to the Relational Database world is never going to be pretty. Bear with me, keeping reading...
Because of #1, I switched to Lumen where Eloquent is turned off by default. It's fast, lean, and still does everything I needed and loved in Laravel.
Each query fits in one of two categories (I suppose this is a form of CQRS):
3.1. Repositories (commands): These deal with changing state (writes) and situations where you need to hydrate an object and apply some rules before changing state (sometimes you have to do some reads to make a write) (also sometimes you do bulk writes and hydration may not be efficient, so just create repository methods that do this too). So I have a folder called "Domain" (for Domain Driven Design) and inside are more folders each representing how I think of my business domain. With each entity I have a paired repository. An entity here is a class that is like what others may call a "model", it holds properties and has methods that help me keep the properties valid or do work on them that will be eventually persisted in the repository. The repository is a class with a bunch of methods that represent all the types of querying I need to do that relates to that entity (ie. $repo->save()). The methods may accept a few parameters (to allow for a bit of dynamic query action inside, but not too much) and inside you'll find the raw queries and some code to hydrate the entities. You'll find that repositories typically accept and/or return entities.
3.2. Queries (a.k.a. screens?): I have a folder called "Queries" where I have different classes of methods that inside have raw queries to perform display work. The classes kind of just help for grouping together things but aren't the same as Repositories (ie. they don't do hydrating, writes, return entities, etc.). The goal is to use these for reads and most display purposes.
Don't interface so unnecessarily. Interfaces are good for polymorphic situations where you need them. Situations where you know you will be switching between multiple implementations. They are unneeded extra work when you are working 1:1. Plus, it's easy to take a class and turn it into an interface later. You never want to over optimize prematurely.
Because of #4, you don't need lots of service providers. I think it would be overkill to have a service provider for all my repositories.
If the almost mythological time comes when you want to switch out database engines, then all you have to do is go to two places. The two places mentioned in #3 above. You replace the raw queries inside. This is good, since you have a list of all the persistence methods your app needs. You can tailor each raw query inside those methods to work with the new data-store in the unique way that data-store calls for. The method stays the same but the internal querying gets changed. It is important to remember that the work needed to change out a database will obviously grow as your app grows but the complexity in your app has to go somewhere. Each raw query represents complexity. But you've encapsulated these raw queries, so you've done the best to shield the rest of your app!
I'm successfully using this approach inspired by DDD concepts. Once you are utilizing the repository approach then there is little need to use Eloquent IMHO. And I find I'm not writing extra stuff (as you mention in your question), all while still keeping my app flexible for future changes. Here is another approach from a fellow Artisan (although I don't necessarily agree with using Doctrine ORM). Good Luck and Happy Coding!
Laravel's Eloquent is an Active Record, this technology demands a lot of processing. Domain entities are understood as plain objects, for that purpose try to utilizes Doctrime ORM. I built a facilitator for use Lumen and doctrine ORM follow the link.
https://github.com/davists/Lumen-Doctrine-DDD-Generator
*for acurated perfomance analisys there is cachegrind.
http://kcachegrind.sourceforge.net/html/Home.html

Example of branch by abstraction for an ASP.NET MVC 3 application where the abstraction is different countries

I work on an ASP.NET MVC 3 application where branches in version control have been created for each country. This makes it difficult sync changes between the branches and the problem will increase as the number of countries increases. I have read about branching by abstraction but have never actually used it so I'm struggling to comprehend how this would be actually be implemented in a reasonably complex project.
Can anyone explain how branching by abstraction can be done for an ASP.NET MVC application where the abstraction is a country, and the application is a n-tier type affair with service and data layers?
A few of the things I can't get my head round are:
Abstracting view stuff. E.g. The aspx/cshtml files, javascript, css
etc.
Abstracting controllers
How do you manage the extra complexity of having all your for code
every country in one branch? (Note, by one branch I mean the default branch, mainline, whatever you want to call it)
How you you manage feature toggles for each country? E.g. Potentially you could have many many features for each country that were not ready for release and controller by a toggle)
How do you select the appropriate country when deploying?
How do you run unit tests for country specific functionality?
UPDATE
I'm not just talking about language changes. Much of the service layer logic for each country is the same, but in certain key areas it's different, likewise for the data layer. Also view content and layout can vary, javascript can vary and controller logic can vary.
Why do you use branches to handle localization? imho it's madness.
There are several ways to do localizations without having one code base per language.
For instance. By making your own view engine on top of an existing one you can load views from external assemblies. Or you can create one view per language.
You can also use string tables in your views to make them localized.
Abstracting view stuff. E.g. The aspx/cshtml files, javascript, css etc.
Javascripts: I have one javascript with all my logic which uses variables instead of strings to show messages. In this way I can load another javascript before the logic script (for instance myplugin.sv.js before myplugin.js to get the swedish language.
The most common way for aspx/cshtml files is to use string tables in them.
Localize css? Why?
Abstracting controllers
huh? Why? Use string tables here too.
How do you manage the extra complexity of having all your for code every country in one branch?
Don't use branches.
How you you manage feature toggles for each abstraction?
huh?
How do you select the appropriate country when deploying?
Use the same site for all languages. Either use the IP address, Accept-Language http header or the user's language preference to select language. Language is specified by setting Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture
How do you run unit tests for country specific functionality?
Don't. The logic should be the same.
Update in response to your comment
I've written my fair amount of systems where content is dynamically loaded into the application/service. I've never used different code bases even if different customers use different features in multi-tenant systems (SaaS).
First of all, you need to accept two things:
a) All content is loaded at all time (not talking about translations, but features).
b) Use proper/standard localization methods, but no need to translate all features to all languages.
What you do is simply control which content to load and use standard techniques to get translated features. The control is made by either checking the current language (Thread.CurrentThread.CurrentCulture.Name) or any homebrewn control.
Ask new questions to get more details.
Update 2
I wouldn't rely on the IoC to provide language specific features, but use reflection and a FeatureProvider class to do that for me.
For instance, let's say that you have a feature called ISalaryCalculator which takes into account all local tax rules etc. then I would create something like this:
// 1053 is the LCID (read about LCID / LocaleId in MSDN)
[ForLanguage(1053)]
public SwedishSalaryCalculator : ISalaryCalculator
{
}
And have a FeatureProvider to load it:
public class FeatureProvider
{
List<Assembly> _featureAssemblies;
public T GetLocalFeature<T>()
{
var featureType = typeof(T);
foreach (var assembly in _featureAssemblies)
{
foreach (var type in assembly.GetTypes().Where(t => featureType.IsAssignableFrom(t))
{
var attribute = type.GetCustomAttributes(typeof(ForLanguageAttribute)).First();
if (attribute.LocaleId == Thread.CurrentThread.CurrentCulture.LCID)
return (T)Activator.CreateInstance(type);
}
}
return null;
}
}
And to get the feature (for the current language):
var calculator = _featureManager.GetLocalFeature<ISalaryCalculator>();
var salaryAfterTaxes = calculator.GetSalaryAfterTax(400000);
In a simple scenario (CMS/not much or shared business logic) you are dealing with just content in different languages and:
Layout (left to right vs right to left) - you will have two CSS files
Localized (translated) content
Layout CSS can be in separate files and be pulled in depending on the User Account's culture or site region setting.
Localization can reside in different assemblies - one for each culture or in separate string table files (as already mentioned).
In a more complex scenario, where you are developing an application for sensitive cultures and regions where:
You have to be careful about the content you display - for example an image can be very offensive in one country but perfectly fine in another country.
Different business logic (e.g. think financial application, etc)
Most of the content issues you can solve with CSS, but even if you need heavily customized views as has already been mentioned you can create a view engine that pulls a view file based on the current culture (e.g. Index.en-Us.cshtml, Index.ru.cshtml, etc)
For the different business rules you must have a good design and architecture utilizing Inversion of control (e.g. dependency injection) and patterns such as the Strategy, state, Template method, etc. Given that you have that in place you will be able to create an IoC container project/assembly per culture at run time and your UI will be unaware of the difference since it will be simply consuming some services defined by those interfaces.
Slightly more tricky if your ViewModels are significantly different between cultures, but if they are you probably want to maybe split View + Controller per culture in different assemblies and again use IoC to configure the routing at run time initialization.
Clearly deploying multi-cultural sites is more complex than non-such and no matter which way you go (site instance per culture or one site instance for all cultures) you will probably want to invest in some tooling to be able to script multi-culture deployment.
And last - regarding the unit tests - if you already have a good IoC based design testing per culture will be a matter of using and configuring the right dependency container prior to running a set of unit tests.
With such a setup the teams of developers should be working in relatively self-contained environment, since your project will be logically and physically be partitioned to support multiple teams working on separate parts of it at the same time. It also shouldn't matter whether on branches or trunk/head. Of course if everything is a big mess in just a few projects and people have to constantly merge in - you are in a very bad state and your future isn't bright.
Final words: It's not about branching - it's about design, architecture, partitioning (solutions, projects and assemblies) and last but not least about automation (build and test).
This is a little off topic, but I believe you're heading in a more difficult direction than you need to. Localization is built into ASP.NET and the MVC framework can take advantage of it also.
The short story is that you basically make a resx for each language you'd like to support. You then use Resources.Global.YourLocalizedStringPropertyName in your views.
This blog post is the long story. Scott Hanselman goes over javascript localization and other finer points. It's definitely worth a read and will probably save you incredible amounts of work to use the built in functionality instead of building it yourself:
http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx

Resources