Using OO PHP in CSS - php

tl;dr - I'd like to know if it is possible to pass an object into a PHP file with CSS headers, such that I can use this object to manipulate various CSS attributes.
What I'm attempting to do, is allow my PHP/CSS file to interact with the other objects/php files in the webpage, e.g. menu item objects. My ultimate goal is to use PHP in the CSS file to count the number of menu items, and apply the appropriate width value in order to space them out evenly on the page.
I use a very simple color based example below to demonstrate my understanding so far...
I understand that for basic usage of PHP in a CSS file, one can do something like:
<?php header("Content-type: text/css");
$dkgreen = '#008400';
body {
background:<?=$white?>;
}
?>
I also understand that OO PHP can be used to achieve a similar thing, e.g.:
class css {
function __construct($args=array()) {
foreach($args as $key => $field) {
$this->{"$key"} = $args["$key"];
}
return $this;
}
}
$css = new css(
array(
bgcolor => '#00FF00',
fgcolor => '#000000',
)
);
body {
background: <?php echo $css->bgcolor; ?>;
color: <?php echo $css->fgcolor; ?>;
}
Results of experimentation
1) OO style
I firstly attempted to make my css class create a singleton object for the CSS, which I tried to retrieve using $css = css::singleton(), along with the getCss() function, instead of $css = new css(...). The idea was that I wouldn't simply initialise another css object which would be useless to me. Attempts to get the values for bgcolor and fgcolor using:
$css = css::singleton();
$css->getCss()->bgcolor;
were unsuccessful.
2) altering the href in the link tag à la style.php?bgcolor=00FF00&fgcolor=000000
This worked beatifully, when I could easily type $bgcolor = $_GET['bgcolor'];, but doesn't seem to me an elegant solution.
Ideally, I'd like to retain an Object-Oriented approach, but if that's not possible, I'll happily settle for a POST approach, (i.e. allow me to use $bgcolor = $_POST['bgcolor'];) to avoid filling up the source code with ugly parameters in the link tag.
I'd also wish to avoid creating multiple .css files, if that is at all possible.
Any tips?
Many thanks,
Owen.

The easiest way to do this is to make your CSS file a PHP file, and link to it.
<link href="style.php" rel="stylesheet" type="text/css" media="all" />
Then, you parse all your code and dump it out at the end.
$css = ''; # all of your compiled CSS after you do what you need to
header("Content-type: text/css");
print $css;
exit;
Now, your CSS is being parsed how you want it to be, and it's being served as CSS.

I don't think it's possible, and that doesn't fit the purpose of CSS.
Edit:
Well basically, CSS is suppose to contain data that apply a style on a well defined structure. So CSS should not even have variables ( this is a big debate ). The "good theorical way" to solve your problem is to generate html code with proper id and classes, so that you don't have to make any calculation using CSS: you only have to apply a style.
Furthermore:
CSS file are made to be cached. If they change all the time, you may have cache problem, or need to ask the file not to be cached. The you might need to generate inline CSS using PHP, but not a CSS file itself.

Related

Put dynamic variables inside Css using Php

i want to put variable inside css but i don't know how to do it. I have created a php file named style.css.php containing this simple example:
<?php $background = 'blue'; ?>
<style type="text/css">
body {background: <?php echo $background; ?>;}
</style>
But is this a good method? I need to create a customizable theme. The other universal stylesheets are in a normal css file.
Please help.
This question already has an answer.
By the way these link will help you to implement php inside css:
https://css-tricks.com/css-variables-with-php/
How to use PHP inside css file
How do i run PHP inside CSS
I think your approach is already good enough, I'm guessing you are including your style.css.php in the head, potentially putting a lot of CSS there, which isn't necessarily a bad thing.
You don't really have to include your CSS files if you need them on every page anyway, putting them directly into the file saves a HTTP Request but makes your file bigger - but bigger file size doesn't matter if you would load the css file anyway. This way you have even finer control over what gets loaded and what does not, which usually shouldn't be necessary.

Store CSS in PHP variable?

I'm a novice php learner, I was experimenting how to link different php files dynamically. While experimenting, I realize I can create variables in my php files and make my template files echoes out the html I need without editing my template files......
for example:
Within about-me.php page, I have included my header.php and footer.php using
<?php include ('includes/header.html'); ?>
<?php include ('includes/footer.html'); ?>
then I create a variable
$page_title = 'CompanyABC';
and echo out in the header.php
$page_title = 'South Asia Exact';
Now my question is can I do this to my inline css also?
for example, I have create a variable, that store all my inline css:
$page_inlinecss = "#SAEcontentR div#certification_certificate {
margin:0 auto 0 auto;
width:580px;
height:464px;
}\n";
then I echo out in my header.php like so:
<style type="text/css">
<?php echo $page_inlinecss; ?>
</style>
I have tried it and it works, but I want to know is it the right way to do it?
There isn't a right way to do inline CSS
Your code will work, it will produce a valid page, and it will look absolutely fine to the user. BUT you shouldn't do it that way.
So, why shouldn't you do it that way?
Maintainability is the main reason that you shouldn't handle CSS this way. It is far easier to manage a separate CSS file than to pick through PHP code looking for CSS rules to change.
It looks like the data you're storing is static, the point of a variable is to store data that can change. Things like the name of the website (Company ABC) are unlikely to change during the execution of the script, so you should include them in the static HTML template.
On top of this are issues like caching (most browsers cache .css files, saving you bandwidth) and accessibility (screen readers may not know how to deal with inline styles & js).
How should you handle dynamic styles?
One way to handle dynamic styles (that is -- styles based on information which will be different on different page loads) with a combination of PHP and CSS is to define class styles in your external document and then use PHP to apply them.
For example, put this in styles.css:
span.greentext { color: #0f0; }
And this in your PHP file:
<span class='<?php echo ($someCondition) ? "greentext" : null; ?>'>Some text</span>
Or, if you have more styles to handle:
Alternatively, you could load a specific stylesheet upon a condition:
<?php if($someCondition): ?>
<link rel="stylesheet" href="styles/conditional.css" type="text/css" media="screen">
<?php endif; ?>
Hope this helps, and please don't use inline CSS, or variables, unless necessary. You'll thank yourself for it when you have to change the site 5 months down the line.
Can you do this? Yes.
Should you do this? Ehh. (No. was a bit harsh...)
Better to store the CSS filename in a php variable, then in the header add:
<link rel="stylesheet" href="<?php echo $this_page_style_sheet; ?>" />
There is no right or wrong in this case.
You may store the CSS in a string and echo it as you see fit. Or you may even embed it in your includes/header.html file. It's up to you.
Personally, if it is a collection of CSS rules, I would keep it in its own CSS file, and just echo the filename when needed.
$css_filename = "/path/to/rules.css";
// ... etc etc
<link rel="stylesheet" href="<?php echo $css_filename; ?>">
This is a beauty and a pitfall of the way the system works. You can do that, it works and it doesn't seem to present any immediate and glaring security issues. I don't know if that was an intended use of PHP, but it works so if it fits your situation you can use it. The pitfall comes when enough of these little workarounds are used that eventually a security issue could arise somewhere, but I don't recall CSS ever being used as a vector for an attack.
You can do this to generate dynamic css
file css.php
<?php
header("Content-Type: text/css");
echo 'p {color:red}';
?>
html (not complete but it should work cross browser)
<link rel="stylesheet" href="css.php" type="text/css" />
<p>This should be red</p>
Some more strict/uptight folks might say that proper CSS doesn't need variables, yadda yadda.
Personally I think if this works, then it's a clever way to add some ease-of-use to CSS. I'm all for it.

Enforcing CSS integrity over imported php pages

I'm trying to import a php file containing a HTML script with separate CSS and js files into another php file which contains my header and footer. The header and footer are from a template which uses a very messy and convoluted CSS which basically has rules for everything in almost 10 different locations/files. When I import my php into this main template page, all the imported page's styles also inherit from the base template which basically overrides my stuff. Is there a way to enforce each php/html script to maintain their own styles without having to inherit from one another while they're being imported from one file to another?
Many Thanks
How are you importing the files?
Is your answer is using include() or require() then the answer is no! When the html code is generated, all this will show it in the same page, that's what all the css and js files are applied to your html.
What you can do is add the css and js files to a file (eg: assets.php), establish an order and then import that into your main.php and resolve all the problems with the classes and ids on your html to avoid overriding.
EDIT: about CSS load order
The order in which you load your CSS files has very little influence in how styles are applied. What styles are applied to a certain element is determined by the specificity of the selectors used in the CSS rule. A higher specificity overrules a lower specificity, even if the style with the lower specificity is declared later.
CSS Specificity: Things You Should Know
Specifics on CSS Specificity
you need to name space both your css and javascript to protect them from being polluted by your header and footer.
there are many name-spacing patterns out there.. but let me suggest a few:
css: for every page you import.. you can run a jQuery script like this:
jQuery(document).ready(function() {
jQuery('body').attr('id','importedPagei');
}
then when you import the css.. you should create a build script that appends the attribute body#importedPagei to every css you are calling
ie this is a sample of the css of the importing page before running your build script:
.style1 {
color:red
}
and after running the jQuery script:
body#importedPagei .style1 {
color:red
}
so let's say that before.. your header template had the following class:
//header.css
h1 {
color: red;
}
and in your imported file you had
//importedFile.css
h1 {
color:blue;
}
then the final outcome in your old solution will have the template header style overriding yours:
//old final outcome
h1 {
color:blue;
}
but with the proposed solution above you will have (as mentioned before):
//importedFile.css
body#importedPagei h1 {
color: red;
}
and since you attached an id attribut to the body node of importedFile.html using jQuery, the html will look like this
<body id="importedFile">
..
<h1>hello world</h1>
..
</body>
so in this case.. using css cascading rules.. the css selector of your imported file is stronger than that of the template.. and so the final style applied will be color: red
javascript:
you can also use a build script to selectively import specific javascript files for specific pages..
another clean way is to use js.node modules.. the problem with javascript is that everything is in the global namespace.. there are some name spacing patterns that you can use.. but node.js provided a built in and very clean solution for it. and so you can have all the javascript in your final code but have node.js take care of compartmentalising it. it all depends on how much time you want to invest in solving this problem

Define php variables that contain both HTML and subsequently, dynamically settable variables for use later in script?

I'm wondering if I want to do may not be possible... My PHP code loops through jpgs and flv files in an image directory and generates content that consists of in some instances HTML, in others CSS combined with dynamically determined values, for example:
'ul.set li.'.$className.
'{background: url(imagessmall/'.$fileName.')
left -2px no-repeat;}'
Since the above (and much longer sections of HTML+variables) occurs more than once in the code, and because it would make the code easier to review and maintain, I'd like to be able to separate out these html + $variable by defining a set of variables up front, then reference them as needed, for example:
$SDImagePreview =
'ul.set li.'.$className.
'{background: url(imagessmall/'.$fileName.')
left -2px no-repeat;}'
.
.
.
//Code that dynamically sets $className and $fileName is here
$write = fwrite($fileCSS, $SDImagePreview);
I've read on stackoverflow and elsewhere about using &, as in &$fieldName to pass values by reference, but haven't found examples of defining a variable that has within it a variable whose value can be set dynamically.
Am I trying to do something that is just not doable? Or are there alternate suggestions re: implementing the general approach I'm describing? Thanks for any suggestions.
Rather than embedding the html in the code itself, I'd like to be able to define a set of variables at the start of the code, then reference them as needed,
Yes its possible you just have to put your CSS directly to your code in the just add :
<style type="text/css" media="screen">
(...) you generate CSS
<?php print $SDImagePreview; ?>
</style>
CSS are most faster to load if is an extarnal .css file for the caching but in your case the CSS need to be generated in PHP so no cache can be done. If you want to have this change the CSS rule already define by other .css file juste put it after.

CodeIgniter - pass variables to CSS

I'm rewriting website on Code Igniter, and i need to load external TTF. MySQL db points path to that TTFs. Can I pass somehow these variables to CSS and make foreach loop to 'loads' these fonts.
I tried
$this->load->vars($data);
First, deal with serving dynamic CSS. My site has a controller called "resource" which allows me to serve CSS, JS, etc. (maybe images in the future). It loads views based upon the segments passed to it in the url.
So, when http://mysite.com/resource/css/main.css is requested:
My Resource controller (.../controllers/resource) handles any specifics of data handling (as is general with an MVC controller). It then loads:
A generic view: ".../views/resources/css.php", passing it the name of the desired css file. This view prints out the header, specifying the Content-Type (important!) and any other generic stuff. Then it proceeds to load:
The actual CSS file specified, here ".../views/resources/css/main.css.php".
It's a little overkill, but allows for a lot of flexibility, like you sound like you need.
Controller:
...
$segments = $this->uri->segment_array();
array_shift($segments); // remove the first two
array_shift($segments);
$content['stylesheet'] = $segments[0] . ".php"; //e.g. main.css.php
$content['data'] = array(); //Font data, etc
$this->load->view('resources/css.php', $content);
..
Generic resources/css.php
This loads up the actual .css.php stylesheet
<?php header("Content-Type: text/css"); // This is key! ?>
/* MySite CSS File (c) 2011 bla bla */
<?php
$this->load->view("resources/css/$stylesheet", $data);
echo "\n";
?>
Specific resources/css/main.css.php
<?php echo "/* I can use PHP in my CSS! */\n"; ?>
body { background-color: <?=$data['bg_color']?>; }
p { font-family: <?=$data['p_font_fam'];?>; }
You probably need to understand how you retrieve data from db and how you display them:
http://codeigniter.com/user_guide/database/index.html
good luck
EDIT:
what you need is probably something like that:
after you have retrieved the links from database and let's say you called them $ttf_links
<?php
foreach($ttf_links as $link){
echo "<link rel='stylesheet' type='text/css' href={$link['row_name']} media='screen' />"
}
?>
and then call the fonts you need in your css
Passing variables to a CSS doesn't work for as far as I know.
I have read something about CSS templating with PHP, but I can't find the link anymore. Will update this answer as soon as I found the link. But you could look for it yourself as well.
Update
Found it!: http://www.barelyfitz.com/projects/csscolor/
The easiest way I see you doing this is with file level CSS and changing values the usual way.
A workaround would be to use CSS in the page itself to load the fonts.
Here is the answer , I have implemented this and works fine
https://ellislab.com/forums/viewthread/220105/#1014374

Categories