Symfony - Insert values programatically into CSS files - php

Ok, here's the scenario. We have a Symfony2 project and the same core code is shared by two websites, the 2nd website simply has its own App folder, with the src and vendor folders symlinked to the 'master' install. This works great and with the specific parameters in the 2nd app folder, allows us to run with a different database and thus offer the same technical solution to two companies. hurrah :)
BUT. We obviously want them styled differently via CSS, the values for which need to come out of the database. I realise we could simply code them, but with future projects in mind, we want them to be in the database and thus easy to update centrally.
So, the problem is how can we insert these database sourced values into the CSS file? I've looked into SASS etc, which would be a step in the right direction, but the values are still defined within the CSS file, not outside it.
We could do a dynamic CSS file, powered by Twig, but that's frankly using a sledgehammer to crack a nut.
Has anyone come across this problem and found a suitable answer?

I did never try it but i think that you can render a css file with Twig like you render any other file. You only have to create a route, a controller and a view.
Sorry did not read last rules..
You could add a datetime stamp in the css mysql-table. Is it changed? Render and save a new version of your css file. Otherwise skip it.
On the other hand Twig uses caching as much as posible so what is the problem?

You could create a service that write a css file in your css folder.
Call this services when you make any changes in the DB. (You can make a listener for that).
You could also use asseticBundle to manage all your css files.

Related

SASS and/or LESS - can I create dynamic CSS files on the fly?

I'm using CakePHP to build my site (if that matters). I have a TON of elements/modules each having their own file and fairly complicated CSS (in some cases).
Currently the CSS is in a massive single CSS file, but for sanity sake (and the below mentioned details), I would like to be able to keep the CSS in it's own respective file - ie css/modules/rotator.css. But with normal CSS, that would call a TON of CSS files.
So, I started looking into SASS or LESS per recommendation. But - it seems these are supposed to be compiled then uploaded. But in my case, each page is editable via the CMS, so a page might have 10 modules one minute, then after a CMS change it could have 20 or 5...etc. And I don't want to have to compile the CSS for every module if it's not going to use it.
Is there a way I can have a ton of CSS files that all compile on the fly?
Side note: I'd also like to allow the user to edit their own CSS for a page and/or module, which would then load after the default CSSs. Is this possible with SASS and/or LESS?
I don't need a complete walkthrough (though that would be awesome), but so far my searches have returned either things that are over my head related to Ruby on Rails (never used) or generic tutorials on each respective CSS language.
Any other recommendations welcome. I'm a complete SASS/LESS noob.
Clarified question:
How do I dynamically (server-side) combine multiple CSS files using LESS? (even a link to a resource that would get me on the right track is plenty!)
If you want to reduce the number of CSS files & you have one huge css file that has all the component css, just link to it on all pages & make sure you set cache headers properly.
They will load the file once and use it everywhere. The one pitfall is initial pageload time; if that's not an issue go with this solution. If it is an issue consider breaking down your compiled CSS files to a few main chunks (default.css, authoring.css, components.css eg.).
Don't bother trying to make a custom css for each collection of components, you will actually be shooting yourself in the foot by forcing users to re-download the same CSS reorganized in different ways.
Check out lessphp (http://leafo.net/lessphp/). It's a php implementation of less and can recompile changed files by comparing the timestamp.
Assuming that 'on the fly' means 'on pageload', that would likely be even slower than sending multiple files. What I would recommend is recompiling the stylesheets whenever a module is saved.
The issue of requiring only necessary modules should be solved by means of CMS. It has nothing to do with SASS or LESS.
If your CMS is aware of which modules current page has, do not run a SASS/LESS compilation (it will be painfully slow unless you implement caching which is not a trivial task). Instead, adjust your CMS's logic so that it includes each module's CSS file.
Advanced CMSs like Drupal not only automatically fetch only necessary CSS files, but also assemble them into a single file and compress it.
And if your CSS is not aware of which modules current page has (e. g. "modules" are simply HTML code that is saved into post body), then you can't really do anything.
UPD: As sequoia mcdowell says in his answer, making users download one large CSS file once is better than making them download a number of lesser CSS files that contain duplicate code. The cumulative size of all those smaller CSS files will turn out to be larger than the size of a full CSS file.

Is there any way to compact or compile PHP/DHTML/JS components?

Ok the title may be confusing so I explain here my idea: lets say we have a kind of component for a web page, lets say it is a simple database-driven table or grid. Hypothetically this "component" works standalone, ie, no dependences but relays in a few mixed languages files: html for the design, php for databasing, javascript for interactivity and a few icons images. So normally we would just have all that in a folder we upload and then use it including the main (php and/or js) files.
I wonder is there is at least a theorical way to pack all the files into a single unique file, like a .jar file or something, and use the component like it was an OCX or DLL, whatever. I'm not talking specifically about having all packed for downloading it to the client machine...the idea is more like creating a one file thing that contains all the needed files inside, correctly linked, etc. And then perhaps have one single "include" and some sort of constructor call, etc.
I don't know if this is a stupid question but I'm just wondering that...if we could have DHTML components, visual components, like an editor, a grid, a charting thing, etc, just packed in a single file. In other words, having something like DLLs...
Sure, Your only problem is how you include the images in that file. But, everything is made of bits and bytes, images too. Images can be incorporated into a php file (but this is a separate question). As for html+css+javascript incorporation into one PHP file , I do not see the issue, this is pretty much what every php user is doing.
As whether this is a good practice or not, Well, depends how you build that file.

Can jQuery plugins be used in cakePHP?

Hello I am not able to understand how to use jQuery plug-ins in cakePHP. I have one plug-in by the name "countdown". It has 2 js files, one html, one css file and a few images. If I were using regular javascript file, I'd have to give a name to my file and call it in the view or in default.ctp using the "$html->script('path/to/file')" function. But now I have other files too, and if I put them in separate folders complying with the cake structure. But then, I would also have to edit the files with changed paths.
Is there an easy way than putting them in separate folders?
I would simply put them all in your (assumed) app/webroot/js/jquery/plugins/<plugin-name>/.
I see the whole package as something that belongs to js folder, not the individual files.

loading css or javascript from non-public directory

is there a way to load css and/or javascript files from outside of the public web directory?
for example on my hosting service i have /public_html but don't want these files to exist in the public directory and want them in a directory outside of the public directory in a sibling directory /system (i am using codeigniter) within the /system/application/view/
Ultimately, Javascript and Stylesheets are processed on the client side. For that reason, there is no solution that would truly hide your javascript or CSS from the public.
One possible solution is to load the required CSS/ Javascript file via PHP using something like file_get_contents() and then outputting that directly to the page using inline styles / scripts.
This doesn't really solve your problem of hiding the code / styles from the public though. It would give you the option of filtering all code and styles through some kind of packer or obfuscatory, although there's no reason you couldn't do that with your static files (and at much less of a processing expense)
Yes -- in a way -- and Minify [http://code.google.com/p/minify/] is one approach.
Look at line 39 of the config file [http://code.google.com/p/minify/source/browse/trunk/min/config.php]. Here you will see where your minified cache sits outside of the web root. Now, I do not know if the source JS and CSS can sit in the same directory as the cache.
Not without a public facing proxy.
You will need to file_get_contents() or include them and then serve them to your page.
You can not just do ../../system and get above the DOCROOT.
They need to be processed by the browser, so they need to be accessible.
If you want to hinder people viewing your source in a human readable way, check out CSS minify and JS packer. These of course are only obfuscating the code. Anyone determined will be able to read your JavaScript and see what it does.
Why don't you want people to read your CSS or JavaScript?
I know what you mean twmulloy, it seems inconsistent to have 'view' related information in different places. However, consider that the JS and CSS files are resources that support the views, rather than parts of the view themselves.
That said, you can achieve what you want in a number of ways. One might be to write a controller that accepts requests for your JS/CSS assets and outputs a header and data from the relevant place (a view file, the database, anywhere in fact). However, this is inefficienty compared to just accepting the 'untidiness' of popping the files in a subfolder of the root level public_html. I, like many commentors above, feel this is the best solution for its speed and appropriateness; just having an 'assets' directory at the same level as the 'system' one, with images, css, js etc inside. You could use an alias or virtual folder to make things feel better for you...
However, there is a third way. There are libraries that do something JUST like what you want, with the added benefit of Minify (from the accepted answer) and compression, or whatever you fancy. The two libraries I know of are called AssetLibPro and Carabiner, and these allow you to specify an asset path (as you want), and then you load your JS and CSS files (with groups e.g. screen, print if needed). They then serve up all related CSS/JS etc as one file; compressed, minified, cached... whatever you need.
Carabiner: http://codeigniter.com/wiki/Carabiner/
AssetLibPro: http://codeigniter.com/forums/viewthread/78931/

how to organize all js, css, php and html code?

Now I know that you can use OOP and MVC to organize, but that is just for PHP.
Let's say, I add a new window that pops up when a user clicks on a link and it displays a form with JS validations and it is CSS styled.
Here we got 4 codes: JS, CSS, PHP and HTML (with some PHP snippets).
How would you organize all these codes? Because when I got 50 windows codes are spreaded everywhere and for me to change behaviour of delete a window, I have to play detective. I crunch everytime I have to add a new window with JS, CSS and so on.
I have thought about the structure. wouldn't it be better if you got a separate "module" for each one of the window. E.g. a folder for each one of the window. In that map you place one CSS-, one JS-, one PHP-, and one HTML-file? Then you got a very nice structure that aren't messy and you dont mix all windows with each other in one big JS and CSS file.
What do you think? And I would appreciate suggestions of how to organize these 4 kind of codes.
I like Django's way to organize folders. Let's try to imagine and adapt it to your php project:
Root folder is the Project folder, let's say the name of the website. It contains
common shared settings and values (ie. database access values, paths etc.), maybe helper functions (not Object Oriented), call it settings.php and/or utils.php or whatever
a media folder that also has its own structure:
css folder, for general css (ie. reset.css and common.css, for defining a general layout)
image folder, for common shared images
js folder, for common shared javascript code
a template folder containing static common pages not belonging to particular categories of the website
Each Root subfolder is an expression of an application of your project (ie. registration, news, announcements, faq, contacts, forum, ...) and contains:
a model folder in which you put your Models in PHP (MVC pattern)
a controller folder where you implement the Controllers in MVC pattern
a view folder in which you put the Views of your MVC pattern (i.e. quite static php pages responsible just to present the results passed by the Views)
a media folder structured exactly in the same way you structured the one for the root folder. In this folder you put elements only belonging to the particular part of the website you're developing.
For connecting the components, you could directly call / include them based on their paths, or you could implement a php file inside the root directory and each subfolder that is responsible for mapping urls and redirect the requests. Call it index.php or urls.php or connector.php, whatever.
It may seem redundant but it is not, and provides a high quality separation of concerns.
I generally have my PHP pages in one folder, (maybe 10 files if it's a medium size site) then a subfolder in there called media, in which I put a css folder, a js folder an img folder, a swf folder etc.
I have 2 css files, one's a reset, the other has the style for the whole site written in chunks. I use a class on the body tag to target different page layouts.
The js folder has jquery, a file that's run on every page, then specific files for individual pages.
This keeps things pretty straight forward really.
If you are looking for examples on how to design an application, having a look at the many frameworks is a good start. Even just their file structure will give you an idea. Typically, they organize their code into modules where both the PHP code and HTML templates also reside. None in particular are better to look at, but try: CakePHP, Symfony, CodeIgniter, or Agavi.
They will not do a great job on suggesting how to organize JavaScript and CSS files, however. When I make an application, I typically only have a handful of CSS files. I am surprised that you seem to need one per page but if you do: embed them. The advantage of external style sheets is completely lost if there is nothing reusable about their styling. JavaScript files, again, if they are not reusable you should simply embed them. Less HTTP requests per page load makes everyone happy.
When you find yourself scouring for a particular file that stubbornly will not surface itself, grep is an invaluable tool. Here is a random article that illustrates its usage.
If you can/need I'd create top level folders for JS, CSS, PHP, etc that would contain code that could be used across different windows. There's no need to have 50 copies of the same CSS file if they are all the same or even mostly the same code.
Then create a folder for each "window" that has seperate css, js, etc folders. Here you could put the files that are specific to that particular window. This way if you're only changing 1 css rule or js function, that is used by every window you could change it in 1 place.
If you ever need to change the rule for just 1 window, put the rule in the "local css" folder for that window and it will override your default. (That is if your HTML Links it after the "global css")
If you expect the same user to open a few of these different popup windows during a single visit, for their sake you need to consolidate your files so they are cached and the end users doesn't need to load all the CSS/JS again on each popup.
The folder approach is fine for the images and the JS. Unless every popup is drastically different, I would suggest a single CSS file for your own sanity. So your folder structure might look like this:
css/
* layout.css
popups/
* add_new
- add_new.js
- logo.png
- add_new.php
* delete
- delete.js
- other_logo.png
- delete.php
Now, before you deploy you can decide if it makes sense to compile your JS into a single file, or if the separate files would be best. (For instance, if the user opens 30 of the 50 windows every visit, use a single file)
If you are only dealing with the file types mentioned, my best experience is to have folders and files separate everything, and it also keeps it organized with everything Super Easy to Find as your Site Grows & Expands!
OK, so as for folders, you want all you're main HTML, PHP files in the:
/public_html/
(or whatever it's called on you're host. ie. The main area with the cgi-bin inside that is viewable as your main web folder).
eg-:
public_html/index.html
public_html/contact-us-by-email.php
public_html/main.html
public_html/archives.php
NEXT is the CSS and Javascript (JS), these will have their own folders inside your /public_html/ folder. and each file ending in .css or .js go in those particular folders obviously...
eg-:
public_html/css/style.css
public_html/css/dark.css
public_html/css/mobile.css
public_html/js/colorpicker.js
public_html/js/contact-form-tips.js
public_html/js/main.js
And that is That! As easy as it comes to remember, and once you are advanced enough at coding this is the best way to do things. The more advanced you get, the more file types, and also the more 'neat' you are going to want to make it look = organized, you may want to add an /includes/ folder before the /css/ /js/ /templates/ /images/ & so on it goes!
I hope this works out for you, or one of them!
THIS IS MY 1st QUESTION ANSWERED, SO I'M PROUD OF MYSELF & HOPE THE POSTER LIKES MY SOLUTION, GOOD LUCK!

Categories